【问题标题】:Typescript inference from arguments从参数推断打字稿
【发布时间】:2020-01-15 07:13:11
【问题描述】:

我正在寻找一种方法让 Typescript 根据函数参数猜测我的函数的返回类型。

function fn<T extends object>(a: T, b: T, property: keyof T): any {
  return a[property] ?? b[property];
}

我想删除 any 以获得正确的返回类型。

interface A {
  foo?: string;
}

const a: A = { foo : 'bar' };
const b: A = {};
const a = fn(a, b, 'foo'); // it should get the string type from inference

我通过使用 ReturnType&lt;typeof T[property]&gt; 来查看 ReturnType&lt;T&gt;,但 Typescript 似乎不支持它。不知道是否可行?

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:

    为属性名称添加另一个类型参数:

    function fn<T, K extends keyof T>(a: T, b: T, property: K): T[K] {
      return a[property] ?? b[property];
    }
    

    注意它会推断string | undefined,而不是string,因为接口A上的foo属性是可选的,所以ab都可能没有它。

    Playground Link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 2021-08-31
      • 1970-01-01
      • 2019-12-29
      • 2019-02-22
      • 1970-01-01
      • 2020-03-22
      相关资源
      最近更新 更多