Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to express a Date Type in TypeScript ?
Next article icon

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:

Table of Content

  • Using the readonly The modifier in TypeScript Classes
  • Creating a 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
How to express a Date Type in TypeScript ?

A

abhay94517
Improve
Article Tags :
  • Web Technologies
  • TypeScript
  • TypeScript-Reference

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 Con
    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 Return a Union Type in TypeScript ?
    In TypeScript, a union type is a powerful way to express a variable that can be one of several types. Union types are used when a function or variable is expected to support multiple types of input. Union types are defined using the pipe (|) symbol between two or more types. This indicates that a va
    4 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 cla
    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
  • How to Deep Merge Two Objects in TypeScript ?
    Merging two objects in TypeScript is a common task, but when dealing with complex nested structures, a deep merge becomes necessary. A deep merge combines the properties of two or more objects, including nested objects, creating a new object with merged values. In this article, we will explore vario
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences