Recursive readonly object type in TypeScript
25 Apr 2021
We already solved several challenges with readonly:
Today we discuss Deep Readonly
We apply readonly modifier to all object types inside our object type recursively if we need to prohibit mutations of the whole object, but not only the first layer.
Recursive conditional types
If we want to make an object immutable for the first layer only, we use normal Readonly
:
To make other layers immutable, we need to apply it recursively.
Solving Unwrapping the Promises, we already used Recursive conditional types:
We need to check if a current value is of an object type. If so, apply DeepReadonly
recursively:
PropertyKey
means everything that can be a key in an object (it's one of built-ins in Typescript):
Check out the solution on Playground
Have a good week ☀️
typescript