从参数推断打字稿

Typescript inference from arguments

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

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

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

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<T> 像这样使用它 ReturnType<typeof T[property]> 但 Typescript 似乎不支持它。不知道可不可以?

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

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