TypeScript: Emulate Parameters built-in
13 August 2023 (Updated 14 August 2023)
On this page
Solution
type MyParameters<T extends (...args: any[]) => unknown> = T extends (
...args: infer Args
) => unknown
? Args
: never
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
// @ts-expect-error
const foo = (arg1: string, arg2: number): void => {}
// @ts-expect-error
const bar = (arg1: boolean, arg2: { a: 'A' }): void => {}
const baz = (): void => {}
type cases = [
Expect<Equal<MyParameters<typeof foo>, [string, number]>>,
Expect<Equal<MyParameters<typeof bar>, [boolean, { a: 'A' }]>>,
Expect<Equal<MyParameters<typeof baz>, []>>,
]
How it works
We use the infer
keyword to capture the argument types and then return them.
TypeScript playground
Tagged:
TypeScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment