TypeScript Readonly Modifier Example

You can make properties readonly by using the readonly keyword. Readonly properties must be initialized at their declaration or in the constructor. 

TypeScript readonly modifier 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

Read more in the below tutorial




Comments