TypeScriptUtility types
Parameters<Type>
Gets the types of a function’s parameters as a tuple.
Example
#TypeScript
function award(student: string, exp: number, reason?: string) {
return `${student}: +${exp} EXP${reason ? ` (${reason})` : ''}`
}
type AwardArgs = Parameters<typeof award>
// type AwardArgs = [student: string, exp: number, reason?: string]
function logged(...args: AwardArgs): string {
const result = award(...args)
console.log('LOG:', result)
return result
}
logged('Emma', 20, 'Flexbox exercise')
logged('Jack', 5)Result
LOG: Emma: +20 EXP (Flexbox exercise) LOG: Jack: +5 EXP
Definition and usage
#Parameters<Type> returns a tuple with the types of a function’s parameters. For (name: string, level: number) => void the result is [name: string, level: number].
It’s useful for creating wrapper functions that accept the same arguments as the original, for example for logging calls, debouncing, or catching errors.
You can pull out a single parameter by index: Parameters<typeof fn>[0] is the type of the first argument.
Syntax
#Syntax
type Args = Parameters<typeof fn>Type parameters
#Type
function type
The function whose parameters you want to get.
Good practices
#- Combine
ParametersandReturnTypeto write generic wrapper functions. - The type of a single argument:
Parameters<typeof fn>[1].
Related entries
#Spotted a mistake or missing an example? Write to us.