const actions = {
setF1: (a: number) => ({
type: 'a',
a
}),
setF2: (b: string) => ({
type: 'b',
b
})
};
type ActionTypes = ?
export default reducer = (state = {}, action: ActionTypes) => {
switch (action.type) {
case 'a':
console.log(`${action.a} is a number`);
return {
...state,
a
}
case 'b':
console.log(`${action.b} is a string`);
return {
...state,
b
}
default:
return state;
}
};
目标是每次我向actions
对象添加一个函数时,reducer都会自动推断switch
语句中的操作返回类型。我正尝试避免需要执行类似action: Action1 | Action2 | Action3
之类的情况。
答案 0 :(得分:1)
一种实现方法是在actions
的定义中使用const assertions,以使编译器不会将type
的属性扩展为string
,其余的是比较简单。
const actions = {
setF1: (a: number) => ({
type: 'a' as const,
a
}),
setF2: (b: string) => ({
type: 'b' as const,
b
})
};
type ActionKeys = keyof typeof actions; // "setF1" | "setF2"
type ActionTypes = ReturnType<typeof actions[ActionKeys]> // { type: "a", a: number } | { type: "b", b: string }