最近我遇到了一个有趣的问题。假设我有一个泛型函数,我怎么能接收它的类型参数的类型('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;
答案 0 :(得分:1)
我相信只有当您的泛型函数至少有一个参数类型为 T
(泛型参数),或者该函数具有类型为 {{1 }}(通用参数)。
有了这些约束,您可以使用 infer
来非常接近。
T
在 playground 上试用。
问题是,这实际上并不详尽或可靠。您必须知道是否需要在函数上使用 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
或 GenericOf
,这意味着您必须知道该函数是否有参数其对应的泛型类型或其对应类型的返回值。
缺点还不止于此。没有办法真正确保您传递的函数是一个通用函数。
看到这种类型了吗?
GenericOf_
基本上就是type GenericOf<F> = F extends (...args: any[]) => infer A ? A : never;
,没有什么特别。只有当程序员假设它是一个实际的通用函数,使用其通用参数作为返回类型时,它才会变得特殊。
不幸的是,我相信这是您目前所能得到的最接近的结果。不过,我很乐意被证明是错误的!