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:
TypeScript Object The ReadonlyArray Type
Next article icon

TypeScript Object Type readonly Properties

Last Updated : 23 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 classes, interfaces, and type aliases.
JavaScript
class ReadonlyExample {   readonly name: string;    constructor(name: string) {     this.name = name;   }    getName(): string {     return this.name;   } }  const obj = new ReadonlyExample("John"); console.log(obj.getName()); 
  • The name property is marked as readonly, meaning it can only be assigned during object initialization via the constructor.
  • The constructor accepts a name parameter and assigns its value to the readonly property.
  • The getName method is used to retrieve the value of the name property.
  • An instance of the ReadonlyExample class is created with the name "John", and the getName method is called to print the name.

Output:

John

More Examples of TypeScript Object Type readonly Properties

Immutable Point Coordinates

JavaScript
interface Point {   readonly x: number;   readonly y: number; }  const p1: Point = { x: 10, y: 20 }; console.log(`Point coordinates: (${p1.x}, ${p1.y})`);  // p1.x = 15; // Error: Cannot assign to 'x' because it is a read-only property. 
  • Defines a Point interface with readonly properties x and y, ensuring the coordinates cannot be modified after initialization.
  • Attempts to reassign p1.x will result in a compile-time error, enforcing immutability.

Output:

Point coordinates: (10, 20)

Readonly Array of Numbers

JavaScript
const numbers: ReadonlyArray<number> = [1, 2, 3, 4, 5]; console.log(numbers);  // numbers.push(6); // Error: Property 'push' does not exist on type 'readonly number[]'. 
  • Creates a ReadonlyArray of numbers, preventing any modification methods like push or pop.
  • Ensures the array remains unchanged throughout its lifecycle, promoting data integrity.

Output:

[1, 2, 3, 4, 5]

Readonly Property in a Class

JavaScript
class Car {   readonly make: string;   readonly model: string;    constructor(make: string, model: string) {     this.make = make;     this.model = model;   }    getCarInfo(): string {     return `${this.make} ${this.model}`;   } }  const myCar = new Car('Toyota', 'Corolla'); console.log(myCar.getCarInfo());  // myCar.make = 'Honda'; // Error: Cannot assign to 'make' because it is a read-only property. 
  • Defines a Car class with readonly properties make and model, set during object instantiation.
  • The getCarInfo method returns the car's make and model.
  • Attempts to modify myCar.make after creation will result in a compile-time error, preserving the object's state.

Output:

Toyota Corolla

Best Practices for Using TypeScript readonly Properties:

  • Initialize During Declaration or Constructor: Assign values to readonly properties either at the point of declaration or within the constructor to ensure they remain immutable.
  • Use for Immutable Data: Apply readonly to properties that should not change after initialization, such as configuration settings or constant values, to prevent unintended modifications.
  • Combine with Readonly<T> Utility Type: Utilize TypeScript's Readonly<T> utility type to create immutable versions of object types, enhancing code safety and predictability.

Next Article
TypeScript Object The ReadonlyArray Type

A

abhiisaxena09
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • TypeScript
  • Geeks Premier League 2023

Similar Reads

  • TypeScript Object Type Optional Properties
    In TypeScript, optional properties are denoted using the ? modifier after the property name in the object type definition. This means that when an object is created, the optional property can either be provided or omitted. Syntax:type TypeName = { propertyName: PropertyType; optionalPropertyName?: O
    3 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
  • TypeScript Object The ReadonlyArray Type
    In this article, we are going to learn about Object The ReadonlyArray Type in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, the ReadonlyArray<T> type is used to create an immutable (read-only) array of elements of ty
    3 min read
  • TypeScript Object Type Property Modifiers
    TypeScript Type Property Modifiers are used to specify each property in an object such as: the type, whether the property is optional, and whether the property can be written to. TypeScript Object Type Property Modifiers:readonly Properties: An object type with readonly properties specifies that the
    3 min read
  • TypeScript Optional Properties Type
    TypeScript Opional properties type provides a way of defining the parts that are not necessarily required. TypeScript Optional Properties TypesOptional Properties are properties that are not required mandatorily and can be omitted when not needed.In TypeScript, you can define optional properties in
    6 min read
  • TypeScript - Access Modifiers and Readonly Properties
    In TypeScript, access modifiers and readonly properties help define how class members (properties and methods) can be accessed and modified. Access modifiers control the visibility of a class member, determining where it can be accessed from. Readonly properties, on the other hand, ensure that a var
    6 min read
  • TypeScript Object Type Excess Property Checks
    In this article, we are going to learn about Object Type Index Signatures in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, excess property checks refer to the behavior where TypeScript checks for extra or unexpected proper
    3 min read
  • How to Create Deep Readonly Type in Typescript?
    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
    3 min read
  • TypeScript Object Tuple Types
    TypeScript provides various features to enhance type safety and developer productivity. One of these features includes Object Tuple Types. This feature ensures that an object follows a consistent shape in our code which results in a reduction in runtime errors and improves code quality. What are Obj
    5 min read
  • TypeScript Object Types
    TypeScript object types define the structure of objects by specifying property types, ensuring type safety and clarity when passing objects as function parameters. Optional properties, denoted with a ? provide flexibility for objects with varying properties. This approach enhances code robustness by
    3 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