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
60. implement UndefinedToNull<T>
Solution:
type UndefinedToNull<T> = T extends undefined ? null : T extends object ? { [K in keyof T]: UndefinedToNull<T[K]>; } : T;
Explanation:
We use conditional types in TypeScript to create a new type based on a condition. In this case, we check if the input type T
is undefined
or not. If it is undefined, we assign the type null
to it. If it's not undefined
, we check whether it is an object or not. If it's not an object, it means it's a non-object type like string
or number
. In this case, we just return the same type T
. If it's an object, we create a mapped type that iterates over all the keys of the object and apply UndefinedToNull
recursively to each key's value.