Recursive Readonly for objects

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

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

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

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

Check out the solution on Playground

Have a good week ☀️

typescriptmedium

Let's chat and have fun 🧑‍💻👩‍💻

No more often than once a week I write 📄 about TypeScript 💪, video playback 📺 and frontend related topics. You can unsubscribe in any time ↘️