Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.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 从函数对象参数推断返回类型_Typescript - Fatal编程技术网

Typescript 从函数对象参数推断返回类型

Typescript 从函数对象参数推断返回类型,typescript,Typescript,在TypeScript中,我可以从如下的泛型参数推断返回类型。当我使用位置参数时,它工作得很好 const handleAndReturnNumber = (n: number) => n const handleAndReturnString = (n: number) => String(n) const doSomething1 = <R extends (n: number) => ReturnType<R>>(handle: R) =>

在TypeScript中,我可以从如下的泛型参数推断返回类型。当我使用位置参数时,它工作得很好

const handleAndReturnNumber = (n: number) => n
const handleAndReturnString = (n: number) => String(n)
const doSomething1 = <R extends (n: number) => ReturnType<R>>(handle: R) => handle(2)


doSomething1(handleAndReturnNumber) // return type of function is number
doSomething1(handleAndReturnString) // return type of function is string

这和你的例子不一样吗

const doSomething2 = <
  R extends { handle: (n: number) => ReturnType<R['handle']> }
>({
  handle,
}: R) => handle(2);
const doSomething2=<
R扩展{handle:(n:number)=>ReturnType}
>({
手柄
}:R)=>手柄(2);

不完全是因为R需要扩展对象/接口而不是函数。这就是您需要的吗?
const doSomething2 = <
  R extends { handle: (n: number) => ReturnType<R['handle']> }
>({
  handle,
}: R) => handle(2);