简体   繁体   中英

Parameters type of a generic function with specific generic type argument, in typescript

Consider this code in a third party package:

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

How can I get InternalComplexType<number> for example?

This fails:

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

typescript playground

So the best way to achieve this is changing the function definition by an interface function definition, such that it works with typescript utility types. Doing typeof func and trying to pass the generic within the typeof wont work at the moment with typescript compiler. Thus the error.

You can do it like this:

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM