Skip to main content

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:

  1. Rename the variable to something other than name.
  2. Turn your file into a TypeScript module by adding an empty export {};:
export {};
const name = 'John';
  1. Strip out the DOM typings from your compiler options. Drop an explicit lib property into tsconfig.json:
{
  "compilerOptions": {
    "lib": ["es6"]
  }
}

Pick any of those three and the error vanishes. Back to writing TypeScript.