Typescript 如何推断函数对象的返回类型?
目标是每次我向Typescript 如何推断函数对象的返回类型?,typescript,typescript-typings,Typescript,Typescript Typings,目标是每次我向actions对象添加函数时,reducer都会在switch语句中自动推断操作返回类型。我试图避免这样的情况,即我需要执行类似于操作:Action1 | Action2 | Action3的操作,一种方法是在定义操作时使用操作,这样编译器就不会将类型属性扩展为字符串,其余的操作相对简单 const actions={ setF1:(a:数字)=>({ 键入“a”作为常量, A. }), setF2:(b:string)=>({ 键入“b”作为常量, B }) }; 类型Actio
actions
对象添加函数时,reducer都会在switch
语句中自动推断操作返回类型。我试图避免这样的情况,即我需要执行类似于操作:Action1 | Action2 | Action3
的操作,一种方法是在定义操作时使用操作,这样编译器就不会将类型
属性扩展为字符串
,其余的操作相对简单
const actions={
setF1:(a:数字)=>({
键入“a”作为常量,
A.
}),
setF2:(b:string)=>({
键入“b”作为常量,
B
})
};
类型ActionKeys=操作类型的keyof;//“setF1”|“setF2”
类型ActionTypes=ReturnType/{type:“a”,a:number}{type:“b”,b:string}
您应该使用枚举
而不是字符串文本
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;
}
};