Close

TypeScript - Readonly Modifier

[Last Updated: Sep 6, 2018]

We can use readonly modifier to mark properties of a class as immutable.

Example

class Person{
    private readonly _name: string;
    private readonly _age: number;

    constructor(name: string, age: number) {
        this._name = name;
        this._age = age;
    }

    get name(): string {
        return this._name;
    }

    get age(): number {
        return this._age;
    }

    displayAsString():void{
        //this._age=30;  error TS2540: Cannot assign to '_age' because
        // it is a constant or a read-only property.
        console.log(this);
    }
}

let person: Person =  new Person("Ashalee", 28);
person.displayAsString();

Output

Person { _name: 'Ashalee', _age: 28 }

Compiled JavaScript code (--target es6):

class Person {
    constructor(name, age) {
        this._name = name;
        this._age = age;
    }
    get name() {
        return this._name;
    }
    get age() {
        return this._age;
    }
    displayAsString() {
        //this._age=30;  error TS2540: Cannot assign to '_age' because
        // it is a constant or a read-only property.
        console.log(this);
    }
}
let person = new Person("Ashalee", 28);
person.displayAsString();

readonly vs const

A variable defined with const keyword must be initialized at declaration. It can be used with any variables but it cannot be used as a class member.

A variable defined with readonly modifier is used for properties only and it's initialization can be deferred to constructor. This modifier prevents us to reassign a property value.

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.0.1
TypeScript - Readonly Modifier Example Select All Download
  • typescript-read-only-properties
    • example-readonly.ts

    See Also