繁体   English   中英

从 function object 参数推断返回类型

[英]Infer return type from function object parameter

在 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

但是,当我使用“命名参数”时,即 function 只接受一个参数,其类型是 object 我不知道如何才能获得与上述代码相同的结果。 可以在TS中做到吗?

const doSomething2 = ({handle}: {handle: Function /* ? how to infer return type here? */ }) => handle(2)
doSomething1({handle: handleAndReturnNumber}) // return type of function should be number
doSomething1({handle: handleAndReturnString}) // return type of function should be string

不是和你的例子一样吗?

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

暂无
暂无

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

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