DEV Community

Pablo Cavalcante
Pablo Cavalcante

Posted on

Difference between Readonly and Const in TypeScript

If you work with TypeScript or have already worked, it's likely that at some point you have asked yourself which would be the difference between Readonly or Const. Well, this article will answer that question. Let's go!

In TypeScript, const and readonly are used to indicate that a value shouldn’t be changed, but they are applied in different ways.

The const keyword is used to declare a constant that has an immutable value. This means that once a value is assigned to a constant using const, it can't be changed later, and that value must be assigned at the time of constant declaration.

In the example below, PI is declared as a constant and assigned the value 3.14. Any further attempts to assign a new value to PI will result in a compilation error

Code example

On the other hand, the readonly keyword is used to declare properties on a class or object that can only be read but not changed outside the scope in which they are defined. In other words, the property can still have its value changed as long as this change occurs within the scope of the class or object. See an example:

Class Person in TypeScript

In the example above, the arn property of the Person class is declared as readonly with a value already assigned. However, in the constructor of the class, this property could still be changed. Now, if there is an attempt to change this value outside the scope of the Person class, TypeScript will raise an error.

In short, const is used to declare constants at declaration time with immutable values, while readonly is used to declare properties of objects or classes that can only be read outside the scope where they were declared.

Well, that's it! See you guys! 👋👨‍💻

Top comments (0)