【发布时间】:2019-03-05 01:10:33
【问题描述】:
在下面的示例中,如何为withoutSwitchReducer 中的action 参数提供正确的类型?
enum ActionTypesEnum {
FOO = 'FOO',
BAR = 'BAR',
}
type ActionTypes = {
type: ActionTypesEnum.FOO,
payload: { username: string }
} | {
type: ActionTypesEnum.BAR,
payload: { password: string },
};
// "withSwitchReducer" works fine as TS can infer the descriminator 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 code below gives as error as "action.payload.username" is not available on "action.payload.password" and vice versa
const withoutSwitchReducer = {
[ActionTypesEnum.FOO]: (action: ActionTypes) => {
return action.payload.username;
},
[ActionTypesEnum.BAR]: (action: ActionTypes) => {
return action.payload.password;
}
};
此处与 Intellisense 的代码相同:TS Playground Link
【问题讨论】:
标签: typescript typescript2.0 typescript3.0