Explanation
This TypeScript challenge involves creating a type that transforms any given type into a deep readonly version of itself. This concept is commonly used in TypeScript to enforce immutability on objects and their nested properties.
TypeScript Concept Involved
The concept involved is TypeScript's advanced type mapping and conditional types, which allow you to iterate over the properties of a type and apply transformations to them. In this case, the transformation is to make each property readonly.
Solution
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends Function ? T[P] : DeepReadonly<T[P]>;
};
type SantaListProtector<T> = DeepReadonly<T>;
- DeepReadonly is a mapped type that iterates over each property P of type T.
- For each property, it checks if the property type T[P] extends Function. If it does, it is left as is (since functions are inherently immutable).
- If T[P] does not extend Function, it is recursively wrapped in DeepReadonly.
- SantaListProtector is then defined as an alias for DeepReadonly, applying this transformation to any type passed to it.
Link to Day one Challenge on TypeHero.dev:- https://typehero.dev/challenge/day-11
That's it! See you in the next Day Challenge.