【发布时间】:2021-04-10 06:19:45
【问题描述】:
最近我遇到了一个有趣的问题。假设我有一个通用函数,我怎么能接收它的类型参数的类型('T' 的类型),类似于仅用于类型参数的 Parameters 或 ReturnType。下一个例子说明了这个问题(函数'GetTypeParameter'是我想知道如何实现的函数):
interface A {
}
function Foo<T extends A>() {
return 'something';
}
// The wanted ability
type ACopy = GetTypeParameter<Foo> // this will return the type A;
【问题讨论】:
-
我认为您至少需要一个函数参数和/或返回值类型为
T。这可能是infer泛型类型的唯一方法 -
同意@Chase,您应该返回
T或使用T作为参数类型 -
对@Chase 所说的话再投一票。此外,如果没有函数参数包含泛型类型,TS 会抛出错误,因此必须始终有一种方法可以通过
Parameters实用程序类型访问它。
标签: javascript typescript generics types type-parameter