Cannot redeclare block-scoped variable 'name'
Older Article
This article was published 8 years ago. Some information may be outdated or no longer applicable.
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:
- Rename the variable to be something else, other than
name. - Use TypeScript modules, and adding an empty
export {};will do the job, like so:
export {};
const name = 'John';
- Configure your compiler options by not adding DOM typings. This can be achieved by adding an explicit
libproperty totsconfig.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!