How can I specify the correct typing for the action
argument in the function withoutSwitchReducer
as shown below?
enum ActionTypesEnum {
FOO = 'FOO',
BAR = 'BAR',
}
type ActionTypes = {
type: ActionTypesEnum.FOO,
payload: { username: string }
} | {
type: ActionTypesEnum.BAR,
payload: { password: string },
};
// The existing "withSwitchReducer" successfully infers the discriminator from action.type
function withSwitchReducer(action: ActionTypes) {
switch (action.type) {
case 'FOO':
return action.payload.username;
case 'BAR':
return action.payload.password;
default:
return null;
}
}
// The issue arises below due to a lack of IntelliSense when trying to access properties that don't exist on certain payloads
const withoutSwitchReducer = {
[ActionTypesEnum.FOO]: (action: ActionTypes) => {
return action.payload.username;
},
[ActionTypesEnum.BAR]: (action: ActionTypes) => {
return action.payload.password;
}
};
For easier understanding, you can view the same code with IntelliSense here: TS Playground Link