This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for TypeScript puzzle on BFE.dev
10. implement Parameters<T>
Here's a possible implementation of MyParameters<T>:
type MyParameters<T> = T extends (...args: infer P) => any ? P : never;
Let's break it down:
- the
T extends (...args: infer P) => anyconditional type checks whether typeTis a function or not. If it is a function,Pwill be set to the tuple type of its parameters, otherwise, it will be set tonever. - If
Tis indeed a function,MyParameters<T>returns its parameter tuple typeP, otherwise, it returnsnever.
With this implementation, we can check the following:
type Foo = (a: string, b: number, c: boolean) => stringtype A = MyParameters<Foo> // [a:string, b: number, c:boolean]type B = A[0] // stringtype C = MyParameters<{a: string}> // Error
And we get the expected output and error for types A and C, respectively.