How To Solve “‘Const’ declarations must be initialized” in TypeScript

Variables can be declared with a const like var or let. A const variable whose value cannot be changed. If you work with const and do not provide the value when initializing, then the error ‘Const’ declarations must be initialized appear. This article will show you the cause and how to fix it.

The cause of the error “‘Const’ declarations must be initialized” in TypeScript

TypeScript has a way of specifying constant variables. The keyword const is an immutable variable. That is, you cannot change the value of the variable. There are other ways to declare a variable using “let”, “var”, etc. var can declare variables like JavaScript. The keyword “let” was introduced with the keyword “const” in ES6, but “let” seems to define a local variable that assigns its own value. However, if you want to limit the scope, you don’t need to change the variable. So, because of this restriction on “let”, we use the “const” for immutable variables. The error occurs when we declare a variable with a const keyword without assigning a value.

Error Example:

type Student = {
	id: number;
	name: string;
};

// Declare a variable with a const keyword without assigning a value
const student: Student;

Error Output:

'const' declarations must be initialized.

In the above example, we declare a student variable with the data type Student. The principle when declaring a constant variable is that we must always load the data at the time of declaration. In the above example, we lacked the data declaration step, so the above error occurred.

Solution for “‘Const’ declarations must be initialized” in TypeScript

Constants must always have a value, so to solve this error, you must always declare a value for the const variable.

Example:

type Student = {
	id: number;
	name: string;
};

// Always declare a value for the const variable
const student: Student = { id: 12, name: "John" };
console.log(student);

In the above example, we assign an object data type to the student variable when this student variable is declared, so the error is resolved.

Output:

{
  "id": 12,
  "name": "John"
}

We cannot assign another object to a constant, but we can change the value inside the properties

Example:

type Student = {
	id: number;
	name: string;
};

const student: Student = { id: 12, name: "John" };

// Change another value of the attribute
student.id = 55;
student.name = "Mary";
console.log(student);

Output:

{
  "id": 55,
  "name": "Mary"
}

Summary

So we’ve solved error “‘Const’ declarations must be initialized” in TypeScript, always remember that constants must contain data when initialized. Hope you will resolve the error quickly.

Leave a Reply

Your email address will not be published. Required fields are marked *