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
13. implement InstanceType<T>
Here's one possible implementation of MyInstanceType<T>
:
type MyInstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;
Explanation:
MyInstanceType
is a type that takes a type parameterT
that extends a constructor function (i.e., a type with anew
signature).- The type
MyInstanceType<T>
evaluates to the type of the instance thatT
creates. - The implementation uses conditional types (
T extends new (...args: any) => infer R ? R : any
) to extract the return typeR
of the constructor functionT
, and return it as the instance type. IfT
is not a constructor function, the typeany
is returned instead.