Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typescript: Handler not returning state #109

Open
phsantiago opened this issue Mar 22, 2020 · 2 comments
Open

Typescript: Handler not returning state #109

phsantiago opened this issue Mar 22, 2020 · 2 comments

Comments

@phsantiago
Copy link

Hi there, first issue here.

These days using redux-act, I found that the handler of reducer.on isn't using state type received in createReducer.

Example:

interface State {
  loading: boolean;
  name?: string;
  office?: office;
  claims?: Array<Claim>;
}

const reducer = createReducer<State>({}, initialState);

reducer.on(loading, (state, payload) => ({
  ...state,
  loading: payload,
  foo: 'bar',
}));

foo: 'bar' isn't in my interface, and don't throw an error in my typings.

It only works when I explict use State interface as result of my handler function.
Example:

reducer.on(loading, (state, payload): State => ({
  ...state,
  loading: payload,
  foo: 'bar',
}));

Only this way I got the expected behaviour:

src/modules/user.ts|31 col 3 error| 2322[QF available]: Type '{ loading: boolean; foo: string; name?: string | undefined; escritorio?: Escritorio | undefined; claims?: Claim[] | undefined; }' is not assignable to type 'State'. Object literal may only specify known properties, and 'foo' does not exist in type 'State'.

@pauldijou
Copy link
Owner

I can reproduce but I have no idea why it's failing to type properly. I'm not a huge TypeScript user myself unfortunately.

// This is the signature of the `on` function. 2nd argument is a Handler<S, P, M>
on<Arg1, P, M={}>(actionCreator: ActionCreatorOrString1<Arg1, P, M>, handler: Handler<S, P, M>): Reducer<S>

// This is the type for a Handler, a function that must return a `S`,
// where `S` is the `State` during `createReducer`
type Handler<S, P, M={}> = (state: S, payload: P, meta?: M) => S

export function createReducer<S>(handlers: Handlers<S> | OnOff<S>, defaultState?: S): Reducer<S>;

@nullhook
Copy link

This seems to be related to type widening issue. The return value is inferred therefore it allows excess properties on the object.

Here's the issue filed with TS: microsoft/TypeScript#241
PR: microsoft/TypeScript#40311 - This didn't land in any version
Heres the playground

Unfortunately, there's nothing you can do dynamically and just have to annotate the handler function manually.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants