Introduction
Cannot redeclare block-scoped variable 'name'.

Cannot redeclare block-scoped variable 'name'.

The problem

For a long time now I've been baffled by the following error message that I frequently saw in my TypeScript applications:

[ts] Cannot redeclare block-scoped variable 'name'.

This error is raised when I try to declare a variable called name:

const name = "John";

The explanation

The fun fact that this is not in fact a bug related to TypeScript but it's a feature of the language. TypeScript uses the DOM typings for the global execution environment and there in fact exists a name property on the global window object. If you don't believe me, open up your browser's console and type in the following:

'name' in window ? 'property exists' : 'property does not exist'; // property exists

(You can also check the property's value but it will return an empty string: window.name; // "".

The solution

There are three solutions to this hitch:

  1. Rename the variable to be something else, other than name.
  2. Use TypeScript modules, and adding an empty export {}; will do the job, like so:
export {};
const name = "John";
  1. Configure your compiler options by not adding DOM typings. This can be achieved by adding an explicit lib property to tsconfig.json, like so:
{
  "compilerOptions": {
    "lib": ["es6"]
  }
}

Either of the above three solutions will remove the error and we can continue to write more TypeScript code!

Author

Tamas Piros

Developer Evangelist, experienced Technical Trainer and Google Developer Expert in Web Technologies. Active conference speaker, passionate about the latest & greatest advancements in web technologies.

View Comments
Next Post

Typescript: Interfaces vs Types

Previous Post

Unsupervised Machine Learning with JavaScript