Borislav Hadzhiev
Thu Mar 17 2022·2 min read
Photo by Guilherme Veloso
Use the readonly
modifier to declare constants in a class. When a class
field is prefixed with the readonly
modifier, you can only assign a value to
the property inside of the classes' constructor. Assignment to the property
outside of the constructor causes an error.
class Person { readonly name = 'Alice'; readonly country = 'Austria'; logCountry() { console.log(this.country); } } const person = new Person(); person.logCountry(); // 👉️ "Austria" console.log(person.name); // 👉️ "Alice"
We used readonly modifiers to prevent assignment to class properties outside of the constructor.
When using this approach, we are still able to change the value of the properties inside of the constructor function.
class Person { readonly name: string = 'Alice'; readonly country: string = 'Austria'; constructor() { this.name = 'Bob'; this.country = 'Belgium'; } logCountry() { console.log(this.country); } } const person = new Person(); person.logCountry(); // 👉️ "Belgium" console.log(person.name); // 👉️ "Bob"
If you don't want to be able to change the values of the readonly
properties
in the constructor, you can use the
static
keyword with readonly
.
class Person { // 👇️ public if you need to access from outside the class public static readonly firstName = 'Alice'; // 👇️ private if you need to access only from inside this class private static readonly country = 'Austria'; // 👇️ protected if you need to access only from this class // and its subclasses protected static readonly age = 30; logProperties() { console.log(Person.firstName); console.log(Person.country); console.log(Person.age); } } console.log(Person.firstName); // 👉️ "Alice"
static
keyword, we define static methods or properties. Static methods and properties are not accessed on instances of the class, they are accessed on the class itself.The firstName
property is marked as
public,
which means that it can be accessed anywhere (inside of the class and outside of
it).
public
when you need to access the specific property from outside the class.Private visibility only allows access from inside the class.
Members marked as protected are only visible to the class itself and its subclasses.
Make sure you are accessing static
properties and methods on the class, e.g.
Person.firstName
, and not on instances of the class.
An alternative approach is to declare a constant outside of the class and use it in the class.
const firstName = 'Alice'; class Person { logName() { console.log(firstName); } } const person = new Person(); person.logName(); // 👉️ "Alice"
Which approach you pick is a matter of personal preference. I'd go with using
readonly
modifiers because I think it's the most direct and intuitive
approach.