Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有嵌套函数的Typescript ReturnType_Typescript - Fatal编程技术网

带有嵌套函数的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 }