Close

TypeScript - Interfaces with Read-Only Properties

[Updated: Sep 6, 2018, Created: Sep 6, 2018]

In TypeScript the interfaces which describe objects, can have read-only properties. The modifier readonly is used for that purpose.

Example

interface Person {
   readonly name: string;
   readonly age: number;
}

let p: Person = {name: "Ashlee", age: 29};
console.log(p);

Output

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

If we try to modify the readonly property a compile time error will occur:

interface Person {
    readonly name: string;
    readonly age: number;
}

let p: Person = {name: "Ashlee", age: 29};
p.age = 30;
console.log(p);

Output

readonly-properties2.ts(7,3): error TS2540: Cannot assign to 'age' because it is a constant or a read-only property.

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.0.1
Interfaces with Read-Only Properties Select All Download
  • typescript-interface-readonly-properties
    • readonly-properties.ts

    See Also