带有嵌套函数的打字稿ReturnType

时间:2019-06-10 21:37:09

标签: typescript

我正在尝试使用ReturnType来生成一种类型,该类型取决于对象上存在的函数的返回类型。

这里是对象:

const foo = {
  bar: (): number => 1,
  quux: (): string => 'a',
};

所需的结果类型为:

type FooLeaves = {
  bar: number;
  quux: string;
};

是否可以将ResultType应用于对象的值,以便将返回类型从嵌套函数中提取出来?

我想我可以调用每个值并采用该值的类型,但这似乎很麻烦

1 个答案:

答案 0 :(得分:7)

使用mapped types非常简单:

type FooLeaves = { [K in keyof typeof foo]: ReturnType<typeof foo[K]> };

这等效于

type FooLeaves = {
  bar: number;
  quux: string;
};

如果您想要更通用的解决方案,则可以使用conditional types创建类似的内容:

type ResultsOf<T> = { [K in keyof T]: T[K] extends (...args: any) => infer R ? R : T[K] }

这还将处理混合使用函数和常规值的情况,例如:

const foo = {
  bar: (): number => 1,
  quux: 'a',
};

type FooLeaves = ResultsOf<typeof foo>; // { bar: number, quux: string }
相关问题