Skip to content

Action helper type guard breaks large reducers #117

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

Open
danishcake opened this issue Jul 18, 2019 · 0 comments
Open

Action helper type guard breaks large reducers #117

danishcake opened this issue Jul 18, 2019 · 0 comments

Comments

@danishcake
Copy link

danishcake commented Jul 18, 2019

The actionCreatorVoid helper method has a 'test' method that acts as a type guard, allowing typescript to deduce the type is 'IAction'.

Modern versions of typescript use this type information to narrow the remaining type, so you can easily end up with compilation errors in your reducers

// problematicActions.ts
export const stringPayloadAction = actionCreator<string>('STRING_PAYLOAD');
export const noPayloadAction1 = actionCreatorVoid('NO_PAYLOAD_1');
export const noPayloadAction2 = actionCreatorVoid('NO_PAYLOAD_2');


// problematicReducer.ts
export type TState = {
}

export function problematicReducer(state: Tstate = {}, action: IAction): TState {
  if (stringPayloadAction.test(action)) {
    // OK: action deduced as IAction<string>
  } else if (noPayloadAction1.test(action)) {
    // OK: action deduced as IAction
  } else if (noPayloadAction2.test(action)) {
    // Error: Typescript deduces action as 'never' within this check
    // as the previous noPayloadAction1 check covered all IAction cases.
  }

  return state;
}

The solution is to change the test methods in helper.ts to return boolean rather than act as type guards.

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

1 participant