Fix - 'Const' declarations must be initialized in TypeScript

avatar

Borislav Hadzhiev

Tue Mar 15 20222 min read

'Const' declarations must be initialized in TypeScript #

The error "const declarations must be initialized" occurs when we declare a variable using const, but don't assign a value to it. To solve the error, specify a value in the same statement in which the variable is declared or use the let keyword instead.

Here is an example of how the error occurs.

index.ts
// ⛔️ 'const' declarations must be initialized.ts(1155) const arr: string[];

We declared the arr variable using the const keyword, but didn't assign a value to it.

To solve the error, we have to assign a value to the const variable in the same statement in which it was declared.

index.ts
const arr: string[] = [];

What value you assign on the variable will depend on its type.

An alternative solution is to use the let keyword to declare your variable.

index.ts
let arr: string[]; arr = ['a', 'b']; arr = ['c', 'd']; console.log(arr); // 👉️ ['c', 'd']

When you use the let keyword, you can reassign the variable as many times as necessary.

On the other hand, variables declared using const cannot be reassigned, which is why the "const declarations must be initialized" error occurs.

If you declare a const variable without a value, you are effectively declaring an empty variable that cannot be reassigned and given a value later on, which must be a mistake.

We use a colon to give the variable a type and an equal sign to assign a value to it.

index.ts
const obj: { name: string } = { name: 'James Doe' };

Note that variables declared using const cannot be reassigned, but they are not immutable.

index.ts
const obj: { name: string } = { name: 'James' }; obj['name'] = 'Carl'; console.log(obj); // 👉️ {name: 'Carl'} // ⛔️ Error: Assignment to constant variable. obj = { name: 'Alan' };

The code snippet shows that we are able to change the value of an object declared using const, however trying to reassign the const variable causes an error - "Assignment to constant variable".

This is because you are not allowed to reassign or redeclare a variable declared using the const keyword.

Use the search field on my Home Page to filter through my more than 1,000 articles.