[英]Find type parameter of generic function in typescript
最近我遇到了一个有趣的问题。 假设我有一个通用的 function,我怎么能接收它的类型参数的类型('T' 的类型),类似于仅用于类型参数的参数或 ReturnType。 下一个示例说明了该问题(function 'GetTypeParameter' 是 function,我想知道如何实现):
interface A {
}
function Foo<T extends A>() {
return 'something';
}
// The wanted ability
type ACopy = GetTypeParameter<Foo> // this will return the type A;
我相信只有当您的通用 function 具有至少一个T
类型的参数(通用参数),或者 function 具有T
类型的返回值(通用参数)时,这才有可能。
有了这些约束,您可以使用infer
来非常接近。
interface Foo {
fooProp: string;
}
// Function with return type of `T`, where `T` is a generic param extending `Foo`
declare function func1<T extends Foo>(): T;
// Function with argument type of `T`, where `T` is a generic param extending `Foo`
declare function func2<T extends Foo>(a: T): number;
// Extract generic param from function return type
type GenericOf<F> = F extends (...args: any[]) => infer A ? A : never;
// Extract generic param from function argument type
type GenericOf_<F> = F extends (a: infer B, ...args: any[]) => any ? B : never;
let f1: GenericOf<typeof func1>;
// ^ Foo
let f2: GenericOf_<typeof func2>;
// ^ Foo
在操场上试一试。
但问题是,这实际上并不详尽或强大。 你必须知道在function上是否需要使用GenericOf
或GenericOf_
,这意味着你必须知道function是否有对应泛型类型的参数或对应类型的返回值。
缺点还不止于此。 没有办法真正确保您传递的 function是一个通用的 function开始。
看到这种类型了吗?
type GenericOf<F> = F extends (...args: any[]) => infer A ? A : never;
这基本上只是ReturnType<F>
,没有什么特别之处。 只有当你,程序员,假设它是一个实际的通用 function,它使用它的通用参数作为它的返回类型时,它才会变得特别。
不幸的是,我相信这是你目前能得到的最接近的。 我很想被证明是错误的!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.