[英]How do I infer the return types of an object of functions?
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;
}
};
The goal is every time I add a function to the actions
object, the reducer would automatically infer the action return type in the switch
statement.目标是每次我向actions
对象添加一个函数时,reducer 都会自动推断switch
语句中的动作返回类型。 I'm trying to avoid the scenario where I need to do something like action: Action1 | Action2 | Action3
我试图避免需要执行以下action: Action1 | Action2 | Action3
的场景action: Action1 | Action2 | Action3
action: Action1 | Action2 | Action3
action: Action1 | Action2 | Action3
. action: Action1 | Action2 | Action3
。
One way of doing that is to use const assertions in your definition of actions
so that the compiler doesn't widen your type
property to string
, the rest is relatively simple.这样做的一种方法是在您的actions
定义中使用const 断言,这样编译器就不会将您的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 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.