How to implement class constants with TypeScript?

Sometimes, we want to implement class constants with TypeScript.

In this article, we’ll look at how to implement class constants with TypeScript.

How to implement class constants with TypeScript?

To implement class constants with TypeScript, we can use the readonly keyword.

For instance, we write

class MyClass {
  readonly myReadOnlyProperty = 1;

  myMethod() {
    console.log(this.myReadOnlyProperty);    
  }
}

to add the myReadOnlyProperty class constant and set it to 1.

If we try to reassign it to another value like

const m = new MyClass()
m.myReadOnlyProperty = 2

then we’ll get a TypeScript compiler error.

Conclusion

To implement class constants with TypeScript, we can use the readonly keyword.