Typescript Series - Parameters Utility Type
Sarmun Bustillo
Posted on August 28, 2022
I'd like to start by saying that I am doing this series to learn and understand better Typescript, so feel free to correct me or contact me.
Parameters
Constructs a tuple type from the types used in the parameters of a function type Type.
Examples:
type T0 = Parameters<() => string> // []
type T1 = Parameters<(s: string) => void> // [s: string]
type T2 = Parameters<<T>(arg: T) => T> // [arg: unknown]
That means our type should look something like
const foo = (arg1: string, arg2: number): void => {}
const bar = (arg1: boolean, arg2: { a: 'A' }): void => {}
const baz = (): void => {}
MyParameters<typeof foo> // [string, number]
MyParameters<typeof bar> // [boolean, { a: 'A' }]
MyParameters<typeof baz> // []
Ok so what do we know so far:
- Receives a function
- Infer the types of the function parameters passed
- Return a tuple of the types of the function parameters, if any (no pun intended) or nothing
type MyParameters<T extends (...args: any[]) => any> = T extends (...args: infer R ) => unknown ? R : never
Let's break it down:
T extends (...args: any[]) => any
You could read this as our type extends a function and could return anything or nothing.
Understanding the infer keyword
The infer keyword can be used within a condition in a conditional type to put the inferred type into a variable. That inferred variable can then be used within the conditional branches.
T extends (...args: infer R ) => unknown ? R : never
So we infer the types of the function parameters. If it does return something, meaning there were parameters, we return the inferred type, otherwise we return never (nothing, ignored by TS)
Thank you!
you can find me here My Twitter
Posted on August 28, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 15, 2024