Readonly Properties in Typescript

Typescript provides a way to indicate props in an object / type, or an entire type, as read only.

Props in an object

Consider this example -

class Fruit {
  readonly name = "apple";
  color = "red";
}

In the code block we have specified the prop name as read-only.

We can very much change the color of an object derived from Fruit.

const apple = new Fruit();
console.log(apple);
// Fruit { name: 'apple', color: 'red' }

apple.color = "blue";
console.log(apple);
// Fruit { name: 'apple', color: 'blue' }

But, we cannot change the name -

apple.name = "orange";
// error TS2540: Cannot assign to 'name' because it is a read-only property

In normal Javascript, you would have defined the property as non-writable using property descriptors to achieve the same effect.

Props in a type

We create types similar to an object, and we can make one or more of the props read-only.

type Fruit = {
  readonly name: string;
  color: string;
};

const newFruit: Fruit = { name: "apple", color: "red" };
console.log(newFruit);
// { name: 'apple', color: 'red' }

newFruit.color = "blue";
console.log(newFruit);
// { name: 'apple', color: 'blue' }

Note that setting name during initialization is allowed, but the prop cannot be changed later.

All props in a type

We can make entire types as read-only by processing it through a Readonly type.

type Fruit = {
  name: string,
  color: string
};

type ReadFruit = Readonly<Fruit>;

let apple: ReadFruit = { name: "apple", color: "red" };
console.log("apple: ", apple);
// apple:  { name: 'apple', color: 'red' }

We get an error if we try to change any prop -

apple.name = "orange";
// error TS2540: Cannot assign to 'name' because it is a read-only property.

In normal Javascript, you can achieve the same effect using Object.freeze().

comments powered by Disqus