How To Declare A Constant In TypeScript?
TypeScript, like most other programming languages, allows developers to create variables to store different values. One of those variable types is the constant.
To declare a constant in TypeScript, you can use the const keyword.
Here is an example:
typescriptconst name = 'Tim';
In this article, I explain everything about constants in TypeScript and show many code examples.
Let's get to it 😎.
The definition
In TypeScript, a constant is a variable that cannot be modified (re-assigned).
To declare a constant, you need to use the const keyword (introduced in ES6 in 2015).
A constant must follow those simple rules:
- It cannot be re-assigned.
- It cannot be re-declared.
- It must be assigned.
Also, a constant is block scoped, AND we cannot access the constant before its declaration.
How to declare a constant?
To declare a constant, you need to use the const keyword AND assign a value to it.
Here is an example:
typescriptconst max = 10;
The max variable is a constant.
⚠️ Remember, setting the value of a constant is a must; failing to do it will result in a compiler error. Re-assigning the value of a constant will also result in an error. ⚠️
Block scope
When declared, a constant is local to the scope in which we declare it.
Confused? Let's have an example to understand this better.
typescriptconst max = 5;
if (true) {
const max = 100;
// Outputs: 100
console.log(max);
}
// Outputs: 5
console.log(max);
As you can see, we create two constants of the same name in this example. Since we declare them in two different scopes, it is acceptable to do it.
Constant objects
When it comes to a constant object, you cannot re-assign its value, just like in the other examples. You can, however, change the value of one of its properties.
Here is an example:
typescriptconst person = {
name: 'Tim'
};
// Allowed.
person.name = 'Bob';
// Not allowed.
person = {};
If you also want to lock the modification of a constant object property, you can create an interface with a readonly property.
Constant arrays
In TypeScript, a constant array acts the same way as the constant object. You cannot re-assign its value, but you can change the elements inside it.
Here is an example:
typescriptconst names = [ 'Tim', 'Bob' ];
// Allowed.
names.push('Alex');
// Allowed.
names[0] = 'Greg';
// Not allowed.
names = [];
Final thoughts
As you can see, defining a constant is easy in TypeScript.
If, however, you want to be able to modify a variable after its initialization, you need to use the let keyword.
Here are some other TypeScript tutorials for you to enjoy: