Get the parameter types of a function using TypeScript

typescript

Using the built-in utility type Parameters<T>, you can easily get the parameter types of a function using TypeScript.

For example, say you have a module that contains the following:

type Options = {
    one: string,
    two: string,
    three: number
}

export const func = (input: Options) => {
    // ...
}

You have access to the exported function, but from outside of the module, you have no way of directly retrieving the Options type. Luckily, TypeScript has a built-in utility type that allows you to retrieve the types of function parameters.

Using Parameters<T>, the consumer of the module can retrieve the Options type by instead using the type Parameters<typeof func>[0] which resolves to the type of the first parameter in the func function.

type Options = Parameters<typeof func>[0]

let options: Options = {
    one: 'foo',
    two: 'bar',
    three: 3
}