Extract function parameter types with TypeScript. Master the infer keyword and function type manipulation in this easy-level challenge on TypeScriptPro.
Extract function parameter types like a pro! 📤
In this easy-level challenge, you'll implement TypeScript's built-in Parameters<T> utility type from scratch. This type extracts the parameter types from a function type and returns them as a tuple. It's an essential tool for working with functions at the type level.
You'll learn how to use conditional types with infer to capture function parameters, a technique that opens the door to powerful function type manipulations in TypeScript.
Implement the built-in Parameters<T> generic without using it.
For example:
const foo = (arg1: string, arg2: number): void => {}
type FunctionParamsType = MyParameters<typeof foo> // [arg1: string, arg2: number]Change the following code to make the test cases pass (no type check errors).
/* _____________ Your Code Here _____________ */
type MyParameters<T extends (...args: any[]) => any> = any
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '../helpers'
function foo(arg1: string, arg2: number): void {}
function bar(arg1: boolean, arg2: { a: 'A' }): void {}
function baz(): void {}
type cases = [
Expect<Equal<MyParameters<typeof foo>, [string, number]>>,
Expect<Equal<MyParameters<typeof bar>, [boolean, { a: 'A' }]>>,
Expect<Equal<MyParameters<typeof baz>, []>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
The Parameters type uses conditional types with infer to extract function parameters.
type MyParameters<T extends (...args: any[]) => any> = T extends (
...args: infer Params
) => any
? Params
: falseBreaking it down:
T extends (...args: any[]) => any constrains T to function typesinfer P captures the parameter types as a tuplenever (though this shouldn't happen due to the constraint)This pattern is fundamental for introspecting function types and is used extensively in TypeScript's utility types and advanced type programming.
This challenge is originally from here.