/ TypeScript

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!

Tamas Piros

Tamas Piros

Tamas is a full stack web developer turned technical trainer who has a decade of experience working with prestigious organisations and has delivered training classes all over the world.

Read More