How can you declare a read-only property in a TypeScript class?

Understanding Read-Only Properties in TypeScript

In TypeScript, a readonly keyword is used to make a property as read-only. Read-only properties are properties that can be read, but not written to. This makes them very useful in certain use-cases where you want to maintain a certain level of immutability in your data.

For example, if you have a class named User and you want the id property of the User to be set only once during the creation of the User object and should not be changed afterwards, you can declare it as:

class User {
  readonly id: number;

  constructor(id: number) { = id;

In the above User class, the id is a read-only property. After a User object is created, the id can't be changed.

let user = new User(1); = 2; // Error: Cannot assign to 'id' because it is a read-only property.

The readonly keyword provides you with a way to enforce stricter type checking on your code. It is used to signify that a property will never change after the initialization. By adding readonly, TypeScript will check that no writes are made to that property outside of an initializer.

Contrarily, some might think, based on experience with other programming languages, that const, static or final keywords could be used for a similar purpose in TypeScript. However, in TypeScript, const is a variable declaration and not applicable to class properties. The static keyword is to declare a static property that belongs to the class, not an instance of the class. The final keyword is not a valid keyword in TypeScript and mainly used in other object-oriented languages like Java.

By employing readonly, you're enhancing the predictability and readability of your code, leading to fewer bugs and easier maintenance. It also embodies one of the key principles in programming - the Principle of Least Privilege - that a particular entity should have no more permission than necessary. In the context of readonly, it's saying the property should not have more privileges than just being read.

Do you find this helpful?