How to Create Deep Readonly Type in Typescript?
Last Updated :
01 Oct, 2024
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:
Output after Declaring a Readonly Property in a ClassCreating 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:
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.
Similar Reads
How to express a Date Type in TypeScript ? In TypeScript, the Date object is used to handle dates and times. To express a Date type, declare a variable with the type annotation Date and assign it a date value. This allows for precise date manipulation and formatting in your TypeScript code.Ways to Express Date Type in TypeScriptTable of Cont
3 min read
How to declare nullable type in TypeScript ? In vanilla JavaScript, there are two primary data types: null and undefined. While TypeScript previously did not allow explicit naming of these types, you can now use them regardless of the type-checking mode. To assign undefined to any property, you need to turn off the --strictNullChecks flag. How
2 min read
How to Check Types in Typescript? Checking types in TypeScript involves methods like typeof for primitive types, instanceof for class instances, and custom type guards for complex type validation. These techniques help ensure variables are correctly typed, improving code safety, and readability, and preventing runtime errors.Here ar
3 min read
How to Exclude Property from Type in TypeScript ? In Typescript, sometimes we need to exclude a property from a type when we want a similar type with some properties excluded or if we want to remove a property from the type. There are several approaches to exclude properties from a type in typescript: Table of Content Using Mapped Types with condit
4 min read
How to check interface type in TypeScript ? Typescript is a pure object-oriented programming language that consists of classes, interfaces, inheritance, etc. It is strict and it statically typed like Java. Interfaces are used to define contacts in typescript. In general, it defines the specifications of an entity. Below is an example of an in
2 min read
TypeScript Object Type readonly Properties In TypeScript, the readonly modifier ensures that a property can be assigned a value only once during initialization and cannot be changed thereafter.This immutability helps prevent accidental modifications to object properties, enhancing code reliability.You can apply readonly to properties in clas
3 min read
How to create conditional types in TypeScript ? Conditional types in TypeScript enable defining types based on conditions, similar to conditional statements in code. They determine different types of values, making functions adaptable to various input types, and enhancing code flexibility and maintainability. Syntax: We can create conditional typ
3 min read
How to Create an Object in TypeScript? TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data.Creating Objects in TypescriptNow, let
4 min read
TypeScript Object readonly Tuple Types In this article, we will learn about Object readonly Tuple Types in Typescript. In TypeScript, an object with read-only tuple types is a type that represents an object with properties where each property has a specific value and the order of properties is fixed, just like a tuple. However, unlike re
3 min read
How to Use Partial Types in TypeScript ? Partial types in TypeScript offer a versatile solution for creating new types with a subset of properties from existing types. This feature proves invaluable in scenarios where you need to work with incomplete data structures or define flexible interfaces. Below are the approaches to using partial t
2 min read