简体   繁体   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;
  }
};

The goal is every time I add a function to the actions object, the reducer would automatically infer the action return type in the switch statement.目标是每次我向actions对象添加一个函数时,reducer 都会自动推断switch语句中的动作返回类型。 I'm trying to avoid the scenario where I need to do something like action: Action1 | Action2 | Action3我试图避免需要执行以下action: Action1 | Action2 | Action3的场景action: Action1 | Action2 | Action3 action: Action1 | Action2 | Action3 action: Action1 | Action2 | Action3 . action: Action1 | Action2 | Action3

One way of doing that is to use const assertions in your definition of actions so that the compiler doesn't widen your type property to string , the rest is relatively simple.这样做的一种方法是在您的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 }

Playground link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeScript:在映射对象中推断特定类型的参数和函数的返回值 - TypeScript: Infer specific types of arguments and return values of functions in a mapped object 链函数和从先前的返回推断类型 - Chain functions and infer types from previous return 是否可以在 typescript 的映射类型中推断函数的返回类型? - Is it possible to infer return type of functions in mapped types in typescript? 根据 function 的返回值推断类型,其中 function 参数是函数的记录 - Infer types on return value of function, where function parameter is a record of functions 如何推断 object 的转换值的类型 - How to infer types of the transformed values of an object Typescript无法推断出函数对象的正确参数类型 - Typescript cannot infer correct argument types for an object of functions 如何在 TypeScript 中推断 object function 参数的确切类型? - How do I infer the exact type of an object function parameter in TypeScript? 如何从 firebase 函数返回 promise 和 object? - How do i return a promise and object from firebase functions? 推断由包含 object 类型声明为“any”的函数返回类型 - Infer a functions return type that is declared as `any` by the containing object type 使用映射类型时,如何在TypeScript中推断对象属性的值? - How can I infer an object property's value in TypeScript when using mapped types?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM