Categories
TypeScript Answers

How to implement class constants with TypeScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *