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
14. implement ThisParameterType<T>
Here's one possible implementation of MyThisParameterType<T>
in TypeScript:
type MyThisParameterType<T> = T extends (this: infer U, ...args: any[]) => any ? U : unknown;
This implementation uses conditional types to extract the this
parameter type U
from a function type T
. If the function type T
has a this
parameter, then U
is inferred to be its type. Otherwise, unknown
is used as the default type.
The implementation works as follows:
T extends (this: infer U, ...args: any[]) => any
checks ifT
is a function type with at least one parameter labeledthis
. If so,U
is inferred to be the type ofthis
.? U : unknown
usesU
as the result type if the condition is true, andunknown
as the result type otherwise.
The examples given in the question show that the implementation produces the expected results for functions with and without a this
parameter.