Learn TypeScript

Understanding the `readonly` modifier

Understanding the `readonly` modifier

In this lesson, we will learn about the readonly modifier that can be added to properties.

readonly modifier syntax

A property can be readonly by putting a readonly keyword before the property name:

type TypeName = {
readonly propertyName: PropertyType;
};

This can be applied to interface and class properties as well as type alias properties.

interface InterfaceName {
readonly propertyName: PropertyType;
}
class ClassName {
constructor(public readonly propertyName: PropertyType) {}
}

An example

We are going to explore the readonly modifier in the code editor below:

TypeScriptOpen exercise in CodeSandbox

The code contains a bob object of type Person.

  • Change the Person type so that the age property is readonly:
🤔

What happens if we try to change the age property on bob after its declaration?

bob.age = 31;
  • Add the following interface and object:
interface Animal {
name: string;
age: number;
}
const barry: Animal = {
name: "Barry",
age: 4,
};
  • Change the Animal type so that the age property is readonly:
🤔

What happens if we try to change the age property on barry after its declaration?

barry.age = 5;
  • Add a class called Vehicle containing a name property and a readonly topSpeed property:
  • Add the following code:
const mini = new Vehicle("Mini", 120);
mini.topSpeed = 125;
🤔

Why does a type error occur on line 2?

  • Now let's output all the values that we attempted to set, to the console:
console.log(bob.age, barry.age, mini.topSpeed);
🤔

The values output to the console are the values we set rather than the initial values. A type error was raised, so why didn't that stop the values from being updated?

Summary

The readonly modifier allows immutable primitive properties to be created. However, this is only compile-time immutability and not runtime immutability.

In the next lesson, we will learn how to create immutable objects and array properties.

Did you find this lesson useful?

Share this lesson on twitter
© 2023 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more