Constants is a variables in TypeScript and it cannot be reassigned after it has been initialized. using constants makes your code more predictable, safer and easier to debug.
1️⃣ What Are Constants in TypeScript?
Constants are created using the const keyword.
Why use constants?
- Safety: Once a value is assigned to a constant, it cannot be changed, which reduces the chance of errors in your code.
- Readability: It makes your code easier to understand because you know that the value will not change.
- Predictability: Constants help you define values that shouldn’t be modified your whole program.
2️⃣ How to Declare Constants in TypeScript
We declare constants using the const keyword in typescript. once a constant is assigned a value, you cannot change it.
Basic Syntax:
const variableName: type = value;
Example:
const pi: number = 3.14; // Declare a constant with a number value
const greeting: string = "Hello, World!"; // Declare a constant with a string value
console.log(pi, greeting); // Outputs: 3.14 Hello, World!
Once declared, you cannot change the value of pi or greeting. Trying to do so will you get result in an error.
Example of Reassignment Error:
const pi: number = 3.14;
pi = 3.14159; // Error: Cannot assign to 'pi' because it is a constant.
3️⃣ Constants with Objects and Arrays
Constants can be used with objects and arrays in typescript. However, while the reference to the object or array cannot be changed, you can modify the contents of the object or array.
Example with Object:
const person: { name: string, age: number } = { name: "John", age: 30 };
// You cannot change the reference to the person object:
person = { name: "Jane", age: 25 }; // Error: Cannot assign to 'person' because it is a constant.
// But you can modify properties of the object:
person.name = "Jane"; // This is valid
person.age = 25; // This is valid
console.log(person); // Outputs: { name: 'Jane', age: 25 }
Example with Array:
const numbers: number[] = [1, 2, 3, 4];
// You cannot change the reference to the array:
numbers = [5, 6, 7, 8]; // Error: Cannot assign to 'numbers' because it is a constant.
// But you can modify the array contents:
numbers.push(5); // Valid
numbers[0] = 100; // Valid
console.log(numbers); // Outputs: [100, 2, 3, 4, 5]
5️⃣ Benefits of Using Constants
- Code Stability:
Once a value is assigned to a constant, it stay the same the whole code. this makes your program more stable and predictable. - Better Debugging:
Because constants can’t be reassigned, they help prevent bugs caused by accidental value changes. If a constant is mistakenly changed, you will get immediate error during compilation. - Improved Readability:
By using constants, you make it clear that the value is fixed and will not change. this improves the readability of your code and other developers can instantly understand the intent behind the value.
6️⃣ Real-World Example: Using Constants in a Program
Let’s see a practical example where we can use constants for configuration settings in a TypeScript program.
Example:
const MAX_ATTEMPTS: number = 3;
const API_URL: string = "https://api.example.com";
const TIMEOUT: number = 5000; // Timeout duration in milliseconds
function fetchData(url: string): void {
let attempts = 0;
while (attempts < MAX_ATTEMPTS) {
try {
console.log(`Attempting to fetch data from ${url}...`);
// Simulate a fetch request
// fetch(url).then(response => response.json());
throw new Error("Request failed"); // Simulate failure
} catch (error) {
attempts++;
if (attempts === MAX_ATTEMPTS) {
console.log("Max attempts reached. Giving up.");
break;
} else {
console.log(`Attempt ${attempts} failed. Retrying...`);
}
}
}
}
fetchData(API_URL);
In this example, the constants MAX_ATTEMPTS, API_URL and TIMEOUT provide easy-to-read configuration values that will not change during runtime.