参数在typescript中具有特定泛型类型参数的泛型函数的类型
在第三方软件包中考虑此代码:参数在typescript中具有特定泛型类型参数的泛型函数的类型,typescript,generics,typescript-generics,Typescript,Generics,Typescript Generics,在第三方软件包中考虑此代码: // A third-party package type InternalComplexType<T> = ...; // not exported export function foo<T>(arg1: T, arg2: InternalComplexType<T>): void {} //第三方软件包 类型InternalComplexType=…;//不出口 导出函数foo(arg1:T,arg2:InternalCo
// A third-party package
type InternalComplexType<T> = ...; // not exported
export function foo<T>(arg1: T, arg2: InternalComplexType<T>): void {}
//第三方软件包
类型InternalComplexType=…;//不出口
导出函数foo(arg1:T,arg2:InternalComplexType):void{}
例如,如何获取InternalComplexType
这失败了:
type SecondArgType = Parameters<typeof foo<number>>[1]; // syntax error
type SecondArgType=参数[1];//语法错误
因此,实现这一点的最佳方法是通过接口函数定义更改函数定义,以便它与typescript实用程序类型一起工作。使用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=T |编号;
导出函数foo(arg1:T,arg2:InternalComplexType):void{}
//为泛型函数创建接口类型
接口foo{
(arg1:T,arg2:InternalComplexType):T
}
类型SecondArgType=参数[1];
首先的问题是,InternalComplexType
不是从第三方软件包导出的。如果我有权访问InternalComplexType
,我甚至不会面对这个问题。@AlirezaMirian我不明白。即使导出了该类型,您也会遇到语法错误。上述解决方案肯定会解决您的语法错误。关于访问导出类型,请参阅此帖子。我明白了,谢谢您抽出时间。关键是我正在寻找一种使用typeInternalComplexType
的方法,它恰好需要基于特定的泛型参数值获取泛型函数的参数。因此,假设我有权访问InternalComplexType
的解决方案是毫无意义的。我想我已经把它命名为InternalComplexType并添加了一条“NotExported”注释:)说明了这一点