【问题标题】:Parameters type of a generic function with specific generic type argument, in typescript具有特定泛型类型参数的泛型函数的参数类型,在打字稿中
【发布时间】:2021-04-02 18:29:45
【问题描述】:

考虑将此代码放在第三方包中:

// A third-party package
type InternalComplexType<T> = ...; // not exported
export function foo<T>(arg1: T, arg2: InternalComplexType<T>): void {}

例如,我怎样才能获得InternalComplexType&lt;number&gt;

这失败了:

type SecondArgType = Parameters<typeof foo<number>>[1]; // syntax error

typescript playground

【问题讨论】:

    标签: typescript generics typescript-generics


    【解决方案1】:

    因此,实现这一点的最佳方法是通过接口函数定义更改函数定义,以便它与 typescript 实用程序类型一起使用。执行typeof func 并尝试在typeof 中传递泛型目前不适用于打字稿编译器。因此错误。

    你可以这样做:

    type InternalComplexType<T> = T | number;
    export function foo<T>(arg1: T, arg2: InternalComplexType<T>): void {}
    
    // create an interface type for you generic function
    interface foo<T>{
       (arg1: T, arg2: InternalComplexType<T>): T
    }
    
    type SecondArgType = Parameters<foo<number>>[1];
    

    【讨论】:

    • 首先的问题是InternalComplexType不是从第三方包导出的。如果我可以访问InternalComplexType&lt;T&gt;,我什至不会遇到这个问题。
    • @AlirezaMirian 我不明白。即使导出了该类型,您也会遇到语法错误。上述解决方案肯定会解决您的语法错误。关于访问导出的类型,请参考这个帖子stackoverflow.com/a/54309851/8523669
    • 我明白了,感谢您抽出宝贵时间。关键是我正在寻找一种使用类型InternalComplexType&lt;number&gt; 的方法,这恰好需要基于特定的泛型参数值获取泛型函数的Parameters。因此,假设我可以访问InternalComplexType 的解决方案毫无意义。我想我通过将其命名为 InternalComplexType 并添加“未导出”注释来明确说明 :)
    猜你喜欢
    • 2018-05-02
    • 2020-03-22
    • 2019-07-05
    • 2021-04-10
    • 1970-01-01
    • 2010-10-04
    • 2022-11-11
    • 2020-12-22
    相关资源
    最近更新 更多