Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Constants

Learn how to declare constants using the const keyword, initialize constant values, work with objects and arrays, and understand the difference between const and let.

Simple Explanation: A constant is a variable binding that cannot be reassigned after initialization. In TypeScript, the const keyword declares block-scoped constants.

What Will We Learn?

Constants are useful for values that should not be reassigned during program execution.

  • Understand the purpose of the const keyword.
  • Declare and initialize constants.
  • Understand the difference between const and let.
  • Work with constant objects and arrays.
  • Understand block scope and reassignment errors.
  • Apply constants in practical programs.

Constants Workflow

Follow these steps to understand how constants are declared and used in TypeScript.

📝
Step 1
Declare

Use the const keyword.

→
📦
Step 2
Initialize

Assign an initial value.

→
🔒
Step 3
Protect Binding

Prevent reassignment.

→
🖥️
Step 4
Use Value

Read and use the value.

1. What Is const?

The const keyword declares a block-scoped variable that must be initialized when it is declared and cannot be reassigned later.

Syntax

const variableName: dataType = value;

Example

const studentName: string = "Rahul";
const studentAge: number = 22;

console.log(studentName);
console.log(studentAge);

Expected Output

Rahul
22

Both constants are initialized during declaration. Their bindings cannot later be assigned different values.

2. Declaring and Initializing Constants

A const declaration requires an initial value. You cannot declare a constant and assign its value later as a separate operation.

Correct Example

const courseName = "TypeScript";
const courseFees = 35000;

console.log(courseName);
console.log(courseFees);

Expected Output

TypeScript
35000

Incorrect Example

// This produces a compilation error:
const courseDuration: number;

// A const declaration must be initialized.
Remember: Initialize a constant at the time of declaration. If a value needs to be assigned later, consider using let instead.

3. Difference Between const and let

Both const and let are block-scoped declarations. The main difference is whether the variable binding can be reassigned.

Example

let marks = 70;
marks = 85;

const passingMarks = 35;

console.log("Marks: " + marks);
console.log("Passing Marks: " + passingMarks);

Expected Output

Marks: 85
Passing Marks: 35
Feature let const
Block-scoped Yes Yes
Must initialize during declaration No Yes
Can reassign the variable Yes No
Can redeclare in the same scope No No
Best Practice: Prefer const when reassignment is unnecessary. Use let when the variable needs a new value.

4. Constants with Strings and Numbers

Constants can store text, numeric values, boolean values, and many other supported types.

Example

const instituteName: string = "CIIT Training Institute";
const courseFees: number = 35000;
const isOnline: boolean = true;

console.log(instituteName);
console.log(courseFees);
console.log(isOnline);

Expected Output

CIIT Training Institute
35000
true

TypeScript can also infer these types automatically, so explicit type annotations are not always necessary when the initial value makes the intended type clear.

5. Constants with Arrays

A constant array cannot be reassigned to another array. However, its elements can still be changed unless additional restrictions are used.

Example

const courses: string[] = ["Java", "Python"];

courses.push("TypeScript");

console.log(courses);

Expected Output

[ 'Java', 'Python', 'TypeScript' ]

The array's contents can be modified, but assigning a completely different array to courses would produce an error.

Incorrect Reassignment

const courses: string[] = ["Java", "Python"];

// Compilation error:
// courses = ["C#", "SQL"];
Remember: const prevents reassignment of the binding; it does not automatically make arrays immutable.

6. Constants with Objects

A constant object cannot be reassigned to a different object, but its existing properties can be modified when their types allow it.

Example

const student = {
    name: "Rahul",
    age: 22
};

student.age = 23;

console.log(student.name);
console.log(student.age);

Expected Output

Rahul
23

The age property is updated successfully. The reference stored in student remains the same.

Preventing Object Reassignment

const student = {
    name: "Rahul"
};

// Compilation error:
// student = { name: "Priya" };

7. Block Scope of Constants

Constants declared using const are accessible only within the block in which they are declared.

Example

if (true) {
    const message = "Welcome to TypeScript";
    console.log(message);
}

Expected Output

Welcome to TypeScript

The constant message can be accessed inside the if block.

Incorrect Access

if (true) {
    const message = "Hello";
}

// Compilation error:
// console.log(message);
Note: The last statement is commented out because message is not accessible outside its block.

8. const vs readonly

The const keyword prevents a variable binding from being reassigned. The TypeScript readonly modifier can prevent a property from being reassigned after initialization.

Example

interface Student {
    readonly id: number;
    name: string;
}

const student: Student = {
    id: 101,
    name: "Priya"
};

student.name = "Amit";

console.log(student.id);
console.log(student.name);

Expected Output

101
Amit

The student's name can be changed because it is not marked readonly.

// Compilation error:
// student.id = 202;
Important: readonly is a TypeScript type-system restriction. It does not automatically freeze an object at runtime.

Practical Example: CIIT Course Registration

Let's use constants to store institute information and a course's details in a registration program.

Example

const instituteName = "CIIT Training Institute";
const courseName = "Dot Net Full Stack";
const courseFees = 35000;

let studentName = "Priya";
let isRegistered = true;

console.log("Institute: " + instituteName);
console.log("Course: " + courseName);
console.log("Fees: " + courseFees);
console.log("Student: " + studentName);
console.log("Registered: " + isRegistered);

studentName = "Amit";

console.log("Updated Student: " + studentName);

Expected Output

Institute: CIIT Training Institute
Course: Dot Net Full Stack
Fees: 35000
Student: Priya
Registered: true
Updated Student: Amit

In this example, institute and course details use const. The student's name uses let because the value needs to be updated.

Common Mistakes

  • Declaring a const without an initial value.
  • Trying to reassign a constant.
  • Assuming a constant object cannot have its properties modified.
  • Assuming a constant array cannot have elements added or removed.
  • Accessing a block-scoped constant outside its block.
  • Confusing const with the readonly property modifier.
Tip: Use const for bindings that should not be reassigned. Use suitable types and read-only modifiers when you need additional restrictions on object properties.

Practice Task

Create a TypeScript program to display course registration information using constants.

  • Institute name: CIIT Training Institute
  • Course name: Java Full Stack
  • Course fees: 30000
  • Student name: Sneha
  • Registration status: true

Use const for values that should not be reassigned. Use let if you want to update the student's name.

Hint

const instituteName = "CIIT Training Institute";
const courseName = "Java Full Stack";
const courseFees = 30000;

let studentName = "Sneha";
const isRegistered = true;

console.log(instituteName);
console.log(courseName);
console.log(courseFees);
console.log(studentName);
console.log(isRegistered);

Expected Output

CIIT Training Institute
Java Full Stack
30000
Sneha
true

Summary

In this lesson, we learned how to declare constants using const, initialize values, compare constants with let, work with arrays and objects, and understand block scope and readonly.

Key Point: A constant binding cannot be reassigned, but an object or array declared with const can still be modified unless additional restrictions are used.