具有特定泛型类型参数的泛型函数的参数类型,在打字稿中

时间:2021-04-02 10:00:51

标签: typescript generics typescript-generics

考虑在第三方包中的这段代码:

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

例如,我如何获得 InternalComplexType<number>

这失败了:

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

typescript playground

1 个答案:

答案 0 :(得分:0)

因此,实现此目的的最佳方法是通过接口函数定义更改函数定义,以便它与 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];