0
0
Typescriptprogramming~5 mins

Readonly utility type in Typescript

Choose your learning style9 modes available
Introduction

The Readonly utility type helps you make an object's properties unchangeable. This means you can protect data from being accidentally changed.

When you want to make sure an object's data stays the same after creation.
When sharing data between parts of a program and you want to avoid accidental changes.
When working with configuration objects that should not be modified.
When you want to clearly show that some data is meant to be constant.
When you want to catch errors early by preventing property changes in your code.
Syntax
Typescript
Readonly<Type>

Type is the object type you want to make read-only.

The result is a new type where all properties are readonly.

Examples
This creates a user object whose name and age cannot be changed.
Typescript
type User = {
  name: string;
  age: number;
};

const user: Readonly<User> = {
  name: "Alice",
  age: 30
};
Trying to change point.x will cause a TypeScript error because it is readonly.
Typescript
type Point = {
  x: number;
  y: number;
};

const point: Readonly<Point> = { x: 10, y: 20 };

// point.x = 15; // Error: Cannot assign to 'x' because it is a read-only property.
Sample Program

This program creates a readonly myBook object and prints its title. Trying to change the title will cause an error.

Typescript
type Book = {
  title: string;
  author: string;
};

const myBook: Readonly<Book> = {
  title: "Learn TypeScript",
  author: "Jane Doe"
};

console.log(myBook.title);

// Uncommenting the next line will cause a TypeScript error
// myBook.title = "New Title";
OutputSuccess
Important Notes

Readonly only affects the top-level properties. Nested objects inside are not automatically readonly.

Use Readonly to help prevent bugs by making data immutable.

Summary

Readonly makes all properties of an object type unchangeable.

It helps protect data from accidental changes.

It is useful for constants, configs, and safer code.