[英]Why is the generic type parameter T “unknown” in the return type? How can I type this function so that the return type is correctly inferred?
typescript 手册( https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints )对通用约束进行了说明:
您可以声明受另一个类型参数约束的类型参数。
在这个人为的示例中,如何正确推断 wrap() 的返回类型中的“T”?
function wrap<T, F extends (() => T)>(cb: F): [T, F] {
return [cb(), cb]
}
function load(): string {
return ''
}
const [
value, // unknown, should be string. Can I get typescript to infer this?
wrapped, // () => string
] = wrap(load)
Typescript 从这样的构造推断T
时存在问题func<T, F extends (() => T)>
。 在这种情况下,通常最好依靠infer 。 对于您的示例,我们可以使用实用程序类型ReturnType ,它在内部使用infer
并完全满足我们的需要:
function wrap<F extends (() => any)>(cb: F): [ReturnType<F>, F] {
return [cb(), cb]
}
function load(): string {
return ''
}
const [
value, // string
wrapped, // () => string
] = wrap(load)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.