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 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; // "".
There are three solutions to this hitch:
name.export {}; will do the job, like so:export {};
const name = 'John';
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!