TypeScript Utility Types - Parameters
What is Parameters?
It is a built-in utility type that extracts the parameter types of a function. It accepts a function type as input and gives back a tuple type that lists the parameter types of the function.
type Parameters<T extends (...args: any) => any> = T extends (..args: infer P) => any ? P: neverHow Does Parameters Work?
function myFunc(a: string, b: number, c: boolean) { //...}
type myParams = Parameters<typeof myFunc>;// [a: string, b: number, c: boolean]- Parameters Utility Type:
Parameters<Type>extracts parameter types from a function typeType.- Applied to
myFunc, it gives[string, number, boolean].
- typeof Operator:
typeof myFuncgets the type of the function.
- Result:
myParamsis a type representingmyFunc’s parameter types.- It’s a tuple:
[a: string, b: number, c: boolean].
You also can extract one item like you would with arrays.
type LastParam = Parameters<typeof myFunc>[2];// booleanThe syntax Parameters<typeof myFunc>[2] gets the third element (a boolean) from the array of parameter types.
Recap
The Parameters utility type in TypeScript is a valuable tool, allowing developers to extract a function’s parameter types and gain insights into the anticipated arguments that the function is designed to handle.
Resources
Thank you
Thank you for your time and for reading this!