Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何推断函数对象的返回类型?_Typescript_Typescript Typings - Fatal编程技术网

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;
  }
};