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

时间:2020-03-10 16:49:25

标签: typescript typescript-typings

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之类的情况。

1 个答案:

答案 0 :(得分:1)

一种实现方法是在actions的定义中使用const assertions,以使编译器不会将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 }

Playground link