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
9. implement NonNullable<T>
Here's the solution for implementing MyNonNullable<T>:
type MyNonNullable<T> = T extends null | undefined ? never : T;
Explanation:
- We define
MyNonNullable<T>as a conditional type. - If
Tis assignable tonullorundefined,MyNonNullable<T>will evaluate tonever. This will excludenullandundefinedfrom the resulting type. - Otherwise,
MyNonNullable<T>will evaluate toT.
That's it! Now we can use MyNonNullable<T> as follows:
type Foo = 'a' | 'b' | null | undefinedtype A = MyNonNullable<Foo> // 'a' | 'b'
The resulting type A will exclude null and undefined from Foo.