繁体   English   中英

如何推断函数对象的返回类型?

[英]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;
  }
};

目标是每次我向actions对象添加一个函数时,reducer 都会自动推断switch语句中的动作返回类型。 我试图避免需要执行以下action: Action1 | Action2 | Action3的场景action: Action1 | Action2 | Action3 action: Action1 | Action2 | Action3 action: Action1 | Action2 | Action3

这样做的一种方法是在您的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM