Cannot redeclare block-scoped variable 'name'
• 1 min read
Older Article
This article was published 8 years ago. Some information may be outdated or no longer applicable.
The problem
This error has tripped me up more times than I’d like to admit:
[ts] Cannot redeclare block-scoped variable 'name'.
It fires when you try to declare a variable called name:
const name = 'John';
The explanation
Here’s the thing: it’s not a bug. TypeScript pulls in DOM typings for the global execution environment, and there’s already a name property sitting on the global window object. Don’t believe me? Open your browser console and type this:
'name' in window ? 'property exists' : 'property does not exist'; // property exists
(You can also check the property’s value but it’ll return an empty string: window.name; // "".)
The solution
Three ways to squash this:
- Rename the variable to something other than
name. - Turn your file into a TypeScript module by adding an empty
export {};:
export {};
const name = 'John';
- Strip out the DOM typings from your compiler options. Drop an explicit
libproperty intotsconfig.json:
{
"compilerOptions": {
"lib": ["es6"]
}
}
Pick any of those three and the error vanishes. Back to writing TypeScript.