带有嵌套函数的Typescript ReturnType
我试图使用带有嵌套函数的Typescript ReturnType,typescript,Typescript,我试图使用ReturnType生成一个类型,该类型取决于对象上函数的返回类型 以下是对象: const foo = { bar: (): number => 1, quux: (): string => 'a', }; 所需的结果类型为: type FooLeaves = { bar: number; quux: string; }; 是否可以对对象的值应用ResultType,以便从嵌套函数中提取返回类型 我想我可以调用每个值并采用该值的类型,但它似乎很粗糙使用
ReturnType
生成一个类型,该类型取决于对象上函数的返回类型
以下是对象:
const foo = {
bar: (): number => 1,
quux: (): string => 'a',
};
所需的结果类型为:
type FooLeaves = {
bar: number;
quux: string;
};
是否可以对对象的值应用ResultType
,以便从嵌套函数中提取返回类型
我想我可以调用每个值并采用该值的类型,但它似乎很粗糙使用以下方法非常简单: 如果您想要更通用的解决方案,您可以使用创建如下内容:
type ResultsOf<T> = { [K in keyof T]: T[K] extends (...args: any) => infer R ? R : T[K] }
type ResultsOf={[K in keyof T]:T[K]扩展(…args:any)=>inferr?R:T[K]}
这也将处理混合函数和常规值的情况,例如:
const foo = {
bar: (): number => 1,
quux: 'a',
};
type FooLeaves = ResultsOf<typeof foo>; // { bar: number, quux: string }
const foo={
条:():编号=>1,
quux:‘a’,
};
类型愚人节=ResultsOf;//{bar:number,qux: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 }