electron-react-typescript-boilerplate
electron-react-typescript-boilerplate copied to clipboard
Action helper type guard breaks large reducers
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.