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
15. implement OmitThisParameter<T>
Here's the implementation of MyOmitThisParameter<T>
type:
type MyOmitThisParameter<T> = T extends (this: any, ...args: infer P) => infer R ? (...args: P) => R : never;
Explanation:
- We use conditional types (
T extends ... ? ... : ...
) to check ifT
extends a function withthis
parameter and rest arguments. - If it does, we use
infer
keyword to capture the parameter type (P
) and return type (R
). - We then create a new function type with the same argument types (
P
) and return type (R
) but omit thethis
parameter. - If
T
doesn't extend such a function, we returnnever
.
Testing our implementation:
function foo(this: {a: string}) {}foo() // Errorconst bar = foo.bind({a: 'BFE.dev'})bar() // OKtype Foo = (this: {a: string}) => stringtype Bar = MyOmitThisParameter<Foo> // () => string
The type Bar
is correctly inferred as a function that takes no this
parameter and returns a string.