DEV Community

Pablo Cavalcante
Pablo Cavalcante

Posted on

1

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! 👋👨‍💻

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay