Skip to content

Type check errors when using StateMapper and actions #137

@lauritzsh

Description

@lauritzsh

I am having trouble writing the correct types for injected props (the I generic from here). The problem is when I have to use both state mapping and actions, the injected props are saying missing props in the state mapper, but they are supplied from the actions.

An example would probably help:

import createStore, { ActionCreator, BoundAction } from 'unistore';
import { connect } from 'unistore/preact';

const state = { count: 0 };
const store = createStore(state);

type Store = typeof store;

type StoreState = typeof state;

const actions: ActionCreator<StoreState> = (store: Store) => ({
  increment(state: StoreState) {
    return { count: state.count + 1 };
  }
});

type ComponentProps = {};

type ComponentState = {};

type InjectedProps = {
  count: number;
  increment: BoundAction;
};

connect<ComponentProps, ComponentState, StoreState, InjectedProps>(
  state => ({ count: state.count }),
  actions
);

Here I would expect the curried function to have a props that is joined by ComponentProps (in this example nothing) and InjectedProps (union of state mapper and actions) for the component. However, the state mapping is giving an error:

Property 'increment' is missing in type '{ count: number; }' but required in type 'InjectedProps'.

This error makes sense to me since it's not satisfying the InjectedProps type. This is a contrived example so using a string such as 'count' would work but I want to use the state mapper for type safety.

Right now I am putting the increment: BoundAction up in ComponentProps as an optional but this makes me do an unnecessary if (this.props.increment) { this.props.increment() } check.

How would I write the typings such that it compiles fine? I made a Gist just in case.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions