Fix - Cannot redeclare block-scoped variable in TypeScript

avatar

Borislav Hadzhiev

Mon Mar 14 20222 min read

banner

Photo by Julia Joppien

Fix - Cannot redeclare block-scoped variable in TypeScript #

The error "Cannot redeclare block-scoped variable" occurs when we redeclare a variable in the same block or when TypeScript uses global typings, which interfere with local variable names. To solve the error, only declare a variable once in a block and use ES modules.

Here is an example of how the error occurs.

index.ts
// ⛔️ Error: Cannot redeclare block-scoped variable 'name'.ts(2451) // lib.dom.d.ts(17330, 15): 'name' was also declared here. const name = 'James Doe';
The name variable is declared somewhere in the typings for the DOM library, so the global type definition clashes with the local variable declaration.

You can solve the error, by converting your file to an ES module.

index.ts
const name = 'James Doe'; console.log(name); // 👉️ "James Doe" export {};

We used the export {} line in our file to mark it as an external module. A module is a file that contains at least 1 import or export statement.

You can also solve the error by renaming the variable.

index.ts
const employeeName = 'James Doe'; console.log(employeeName); // 👉️ "James Doe"

The local variable name does not clash with the global typings, so the error is resolved.

The error also occurs if you redeclare a variable in the same scope.

index.ts
const country = 'Germany'; // ⛔️ Cannot redeclare block-scoped variable 'country'.ts(2451) const country = 'Germany';

If you need to change the value of a variable, use the let keyword to declare it and change its value without re-declaring it.

index.ts
let country = 'Germany'; country = 'Austria'; console.log(country); // 👉️ "Austria"

However, note that you could use the same variable name to declare a variable in different blocks.

index.ts
const country = 'Germany'; if (Math.random() > 0.5) { const country = 'Austria'; console.log(country); // 👉️ "Austria" } console.log(country); // 👉️ "Germany"

The curly braces allow us to create a block. Here is the same example, but without the if statement.

index.ts
const country = 'Germany'; { const country = 'Austria'; console.log(country); // 👉️ "Austria" } console.log(country); // 👉️ "Germany"

If none of the suggestions above work, you can try using an immediately invoked function expression.

index.ts
const country = 'Germany'; (function () { const country = 'Austria'; console.log(country); })(); console.log(country); // 👉️ "Germany"

The function in the example above gets invoked immediately as the script is ran.

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