【问题标题】:Find type parameter of generic function in typescript在打字稿中查找泛型函数的类型参数
【发布时间】: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


【解决方案1】:

我相信只有当您的泛型函数有至少一个参数类型为T(泛型参数),或者该函数的返回值类型为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

playground 上试用。

但问题是,这确实不是详尽无遗或健壮的。您必须知道是否需要在函数上使用GenericOfGenericOf_,这意味着您必须知道该函数是否具有对应泛型的参数类型或其对应类型的返回值。

缺点还不止于此。没有办法真正确保您传递的函数是一个通用函数

看到这种类型了吗?

type GenericOf<F> = F extends (...args: any[]) => infer A ? A : never;

基本上就是ReturnType&lt;F&gt;,没有什么特殊。只有当您作为程序员假设它是一个使用其泛型参数作为其返回类型的实际泛型函数时,它才会变得特别

不幸的是,我相信这是你目前能得到的最接近的结果。不过我很想被证明是错误的!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-05
    • 2018-05-02
    • 2020-03-22
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2023-02-22
    相关资源
    最近更新 更多