TypeScript readonly Modifier Example

This post shows how to use a readonly modifier in TypeScript with an example.

Understanding readonly modifier with an example

You can make properties readonly by using the readonly keyword. 
Readonly properties must be initialized at their declaration or in the constructor. 
For Example:
class Employee{
    readonly id: number;
    public firstName: string;
    readonly lastName: string;

    constructor(id: number, firstName: string, lastName: string){
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public getFullName(){
        return this.firstName + ' ' + this.lastName;
    }
}

// create Employee class object
let employee = new Employee(100, 'Ramesh', 'Fadatare');
employee.id = 200; // Error: Cannot assign to 'id' because it is a read-only property.
employee.lastName = 'Kapoor'; // Error: Cannot assign to 'lastName' because it is a read-only property
console.log(employee);
console.log(employee.getFullName());
Notice that the above code gives below compilation error:
employee.id = 200; // Error: Cannot assign to 'id' because it is a read-only property.
employee.lastName = 'Kapoor'; // Error: Cannot assign to 'lastName' because it is a read-only property

Reference




Comments