Borislav Hadzhiev
Tue Mar 15 2022·2 min read
Photo by Freddie Marriage
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.
// ⛔️ '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.
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.
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.
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.
const obj: { name: string } = { name: 'James Doe' };
Note that variables declared using const
cannot be reassigned, but they are
not immutable.
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.