beraliv

Recursive readonly object type in TypeScript

Example of DeepReadonly use
Example of DeepReadonly use

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:

Readonly solution
Readonly solution

To make other layers immutable, we need to apply it recursively.

Solving Unwrapping the Promises, we already used Recursive conditional types:

Example of recursive conditional types
Example of recursive conditional types

We need to check if a current value is of an object type. If so, apply DeepReadonly recursively:

Solution
Solution

PropertyKey means everything that can be a key in an object (it's one of built-ins in Typescript):

All possible keys for an object type
All possible keys for an object type

Check out the solution on Playground

Have a good week ☀️

typescript

Comments

Alexey Berezin profile image

Written by Alexey Berezin who loves London 🏴󠁧󠁢󠁥󠁮󠁧󠁿, players ⏯ and TypeScript 🦺 Follow me on Twitter