Open In App

How to Create Deep Readonly Type in Typescript?

Last Updated : 01 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In TypeScript, the readonly access modifier is a powerful tool that ensures immutability by marking properties of a class as immutable. Once a property is markedreadonly, it cannot be reassigned. This is highly useful for maintaining consistent and safe data structures, especially in scenarios such as state management.

These are the following ways to create deep readonly type in Typescript:

Using the readonly The modifier in TypeScript Classes

TypeScript provides the readonly modifier that allows us to mark class properties as immutable. This immutability means the property can only be assigned a value either during its declaration or in the class constructor. Any attempt to modify the property after this will result in a compile-time error.

Example: Declaring a Readonly Property in a Class. Consider the following example where a Person class has a readonly property called birthDate:

JavaScript
class Person {
    readonly birthDate: Date;

    constructor(birthDate: Date) {
        this.birthDate = birthDate;
    }
}

const person = new Person(new Date(1990, 12, 25));
person.birthDate = new Date(1991, 12, 25);
// Compile-time error

Output:

Screenshot-2024-10-01-150543
Output after Declaring a Readonly Property in a Class

Creating a Deep Readonly Type in TypeScript

The DeepReadonly Type is a utility that enforces immutability at every level of an object. This is especially important when working with complex data structures like nested objects or arrays, where immutability must be preserved across all layers.

Recursive DeepReadonly Type

To implement DeepReadonly, we use TypeScript's conditional types and mapped types to recursively traverse all properties and mark them as readonly.

Here's how we define a DeepReadonly type:

type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};

Example: Let's use the DeepReadonly type on a more complex object

JavaScript
// Define the DeepReadonly utility type
// For arrays,    apply DeepReadonly to each element
type DeepReadonly<T> = T extends (infer U)[]
    ? ReadonlyArray<DeepReadonly<U>> 
    : {
          readonly [K in keyof T]: T[K] extends object
              ? DeepReadonly<T[K]> 
              // Recursively apply DeepReadonly for nested objects
              : T[K];
              // Otherwise, keep the original type
      };

// Define the Person type
type Person = {
    name: string;
    address: {
        city: string;
        country: {
            name: string;
        };
    };
};

// Create a person object of type DeepReadonly<Person>
const person: DeepReadonly<Person> = {
    name: "Prateek",
    address: {
        city: "Delhi",
        country: {
            name: "India",
        },
    },
};

// Accessing properties (no errors)
console.log(person.name);                  // "Prateek"
console.log(person.address.city);          // "Delhi"
console.log(person.address.country.name);  // "India"

// Attempting to modify properties (will give errors)
// These lines should cause TypeScript errors
person.name = "Doe";                      
// Error: Cannot assign to 'name' because it is a read-only property
person.address.city = "LA";                
// Error: Cannot assign to 'city' because it is a read-only property
person.address.country.name = "Canada";    
// Error: Cannot assign to 'name' because it is a read-only property

Output:

Screenshot-2024-10-01-151127

Conclusion

In TypeScript, immutability can be enforced using the readonly modifier for class properties. While readonly works well for simple properties, complex nested objects require a deeper level of immutability. The DeepReadonly type addresses this need by recursively applying the readonly constraint to every property, ensuring that all levels of an object are truly immutable.


Next Article

Similar Reads