【问题标题】:How do I infer the return types of an object of functions?如何推断函数对象的返回类型?
【发布时间】:2020-06-22 15:01:57
【问题描述】:
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 的事情。

【问题讨论】:

  • 您应该使用enum 而不是字符串文字

标签: typescript typescript-typings


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-23
    • 2014-12-10
    • 2020-09-28
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多