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
12. implement ReturnType<T>
Here's one possible implementation of MyReturnType<T>
:
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
This type extends the function type T
and uses the infer
keyword to extract the return type R
. If T
is not a function type, the return type is never
.
With this implementation, we can test the example from the question:
type Foo = () => {a: string};type A = MyReturnType<Foo>; // {a: string}
This assigns the type {a: string}
to the variable A
, as expected.