In this section, we are going to learn about immutable data structures. An immutable data structure is an object that doesn't allow us to change its value. The easiest way to implement an immutable data structure in TypeScript is to use classes and the readonly keyword:
class Person {
public readonly name: string;
public readonly age: number;
public constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const person = new Person("Remo", 29);
person.age = 30; // Error
person.name = "Remo Jansen"; // Error
The preceding code snippet declares a class named Person. The class has two public properties, named name and age. These two properties have been flagged as readonly. As we can see in the code snippet, when we try to update the values of the class properties, a compilation error is thrown.
The...