首页 > 解决方案 > 如何推断函数对象的返回类型?

问题描述

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.

标签: typescripttypescript-typings

解决方案


一种方法是在您的定义中使用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 }

游乐场链接


推荐阅读