typescript - 如何推断函数对象的返回类型?
问题描述
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
.
解决方案
一种方法是在您的定义中使用const 断言actions
,以便编译器不会将您的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 }
推荐阅读
- javascript - Is there a way to increase specificity by adding the element with Emotion?
- javascript - Electron adding files to public folder after build fails
- python - 找不到文件目录错误。请帮助。FileNotFoundError:[Errno 2] 没有这样的文件或目录:'script.py'
- tensorflow - 使用 [image,label] = dataset.take(2) 返回两个元组而不是一个
- android - 为什么 React 不在 Android 操作系统上呈现列表
- python - 在 Keras 中获取多输出模型的类
- java - 试图找到回文数
- python - 列出并使用我自己的函数中定义的变量
- yii2 - 将 phpGrid 与 YII2 集成
- java - 杰克逊 - 马歇尔 XML 到 POJO 无法识别的字段错误