[英]Typescript ReturnType with nested functions
我正在尝试使用ReturnType
生成一个类型,该类型取决于生活在对象上的函数的返回类型。
这是对象:
const foo = {
bar: (): number => 1,
quux: (): string => 'a',
};
所需的结果类型是:
type FooLeaves = {
bar: number;
quux: string;
};
是否可以将ResultType
应用于对象的值,以便从嵌套函数中提取返回类型?
我想我可以调用每个值并采用它的类型,但它似乎很hacky
使用映射类型非常简单:
type FooLeaves = { [K in keyof typeof foo]: ReturnType<typeof foo[K]> };
这相当于
type FooLeaves = {
bar: number;
quux: string;
};
如果您想要更通用的解决方案,可以使用条件类型来创建如下内容:
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 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.