Get argument types for function / class constructor
Solution 1:
Typescript now has the ConstructorParameters
builtin, similar to the Parameters
builtin. Make sure you pass the class type, not the instance:
ConstructorParameters<typeof SomeClass>
ConstructorParameter Official Doc
Parameters Official Doc
Solution 2:
With TypeScript 2.8 you can use the new extends
keyword:
type FirstArgument<T> = T extends (arg1: infer U, ...args: any[]) => any ? U : any;
type SecondArgument<T> = T extends (arg1: any, arg2: infer U, ...args: any[]) => any ? U : any;
let arg1: FirstArgument<typeof foo>; // string;
let arg2: SecondArgument<typeof foo>; // number;
let ret: ReturnType<typeof foo>; // string;