How to get argument types from function in Typescript

Typescript now comes with a predefined Parameters<F> type alias in the standard library which is almost the same as ArgumentTypes<> below, so you can just use that instead of creating your own type alias.

type TestParams = Parameters<(a: string, b: number) => void> // [string, number]

Then to get for example the second parameter's type you can use the numeric indexing operator:

type SecondParam = TestParams[1] // number

Original answer:


Yes, now that TypeScript 3.0 has introduced tuples in rest/spread positions, you can create a conditional type to do this:

type ArgumentTypes<F extends Function> = F extends (...args: infer A) => any ? A : never;

Let's see if it works:

type TestArguments = ArgumentTypes<typeof test>; // [string, number]

Looks good. Note that these beefed-up tuples also capture things like optional parameters and rest parameters:

declare function optionalParams(a: string, b?: number, c?: boolean): void;
type OptionalParamsArgs = ArgumentTypes<typeof optionalParams>; 
// [string, (number | undefined)?, (boolean | undefined)?]

declare function restParams(a: string, b: number, ...c: boolean[]): void;
type RestParamsArgs = ArgumentTypes<typeof restParams>;
// [string, number, ...boolean[]]

Hope that helps. Good luck!

Tags:

Typescript