简体   繁体   English

带有嵌套函数的Typescript ReturnType

[英]Typescript ReturnType with nested functions

I'm trying to use ReturnType to generate a type that depends on the return types of functions living on an object. 我正在尝试使用ReturnType生成一个类型,该类型取决于生活在对象上的函数的返回类型。

Here is the object: 这是对象:

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

The desired resulting type is: 所需的结果类型是:

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

Is it possible to apply a ResultType to the values of the object in order to pull the return types out of the nested functions? 是否可以将ResultType应用于对象的值,以便从嵌套函数中提取返回类型?

I guess I could invoke each value and take the type of that, but it seems hacky 我想我可以调用每个值并采用它的类型,但它似乎很hacky

It's pretty straightforward using mapped types : 使用映射类型非常简单:

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

This is equivalent to 这相当于

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

If you'd like a more generic solution, you might use conditional types to create something like this: 如果您想要更通用的解决方案,可以使用条件类型来创建如下内容:

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

This will also handle the cases where you mix functions and regular values, for example: 这也将处理混合函数和常规值的情况,例如:

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

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM