typescript

How to Fix the “Cannot redeclare block-scoped variable” Error in TypeScript

Are you experiencing the “Cannot redeclare block-scoped variable” error in TypeScript? This error can occur for two reasons:

  1. Using variable names that clash with TypeScript global typings.
  2. Redeclaring a variable in the same block scope.
The "cannot redeclare block-scoped variable" TypeScript error occuring in VS Code.
The “cannot redeclare block-scoped variable” error occurring in VS Code.

We’ll look at solutions for these possible causes in this article.

Fix for: using variable names that clash with TypeScript global typings

The “Cannot redeclare block-scoped variable” error occurs if you declare a variable with a name that clashes with one declared in TypeScript global typings.

index.ts

// ❌ Cannot re-declare block-scoped variable "name".
const name = 'Coding Beauty';

console.log(name);

To fix the error in this case, convert your file to an ES module, like this:

index.ts

// ✅ variable declared successfully
const name = 'Coding Beauty';

console.log(name); // Coding Beauty

export {};

The export {} statement indicates that the file is an ES module. In TypeScript, any file containing a top-level import or export is considered to be a module.

Without top-level import or export declarations, the file gets treated as a script whose contents are available in the global scope (and to other modules). This is what causes the name clash between our name variable and the name variable declared in TypeScript global typings.

Another way to fix this is to use another name to declare the variable that does not clash with the global typings.

index.ts

// ✅ variable declared successfully
const theName = 'Coding Beauty';

console.log(theName); // Coding Beauty

export {};

Fix for: redeclaring a variable in the same block scope

The “cannot redeclare block-scoped variable” error will also occur if you try to declare a variable using a name previously used in the same block scope.

const language = 'JavaScript';

// ❌ Cannot redeclare block-scoped variable 'language'.
const language = 'PHP';

You can easily fix the error in the case by using a different name for the new variable.

const language = 'JavaScript';

// ✅ variable declared successfully
const language2 = 'PHP';

If you intended to assign a new value to the variable, the proper way to do this is to declare the variable with the let keyword, and change its value without redeclaring it.

// declare with "let" keyword
let language = 'JavaScript';

// reassign without redeclaring
language = 'PHP';

console.log(language); // PHP

Note

Unlike const or let, the var keyword doesn’t complain about redeclared variables.

var language = 'JavaScript';

// No error thrown
var language = 'PHP';

Redeclaring variables can cause tricky bugs in your code, and this is one reason to avoid using the var keyword.

You can declare a variable with the same name in a nested block. The variable in the nested block is separate from the one declared in the outer scope.

let color = 'red';

if (true) {
  let color = 'yellow';

  console.log(color); // yellow
}

console.log(color); // red

Note

If you use var keyword to do this, it will override the value of the variable in the outer scope.

var color = 'red';

if (true) {
  var color = 'yellow';

  console.log(color); // yellow
}

console.log(color); // yellow

Another reason to avoid using var.

It doesn’t have to be an if block, we can do this in any nested block designated with curly braces ({ and }).

let color = 'red';

{
  let color = 'yellow';

  console.log(color); // yellow
}

console.log(color); // red

Fix: use an IIFE

Another way to fix the error is to wrap the code containing the variable with an immediately invoked function expression (IIFE). IIFEs are functions that run as soon as they are defined, and they can help to avoid name clashes that cause this error.

const fruit = 'Apple';

(() => {
  const fruit = 'Banana';

  // ✅ variable declared successfully
  console.log(fruit); // Banana
})();

console.log(fruit); // Apple

This fix also solves the issue of TypeScript global typing clashes we looked at earlier.

index.ts

(() => {
  const name = 'Coding Beauty';

  console.log(name); // Coding Beauty
})();

How to Fix the Cannot Find Name ‘it’ Jest Error in TypeScript

To fix the “cannot find name ‘it'” Jest error, install the type definitions for Jest with npm i -D @types/jest and add them to the types array in your tsconfig.json file.

This error occurs when you try to use the it() function from Jest in a TypeScript file, but TypeScript cannot find the type definitions for the package.

Here is an example of the error occurring in Visual Studio Code:

The "cannot find name it" Jest error occurring in Visual Studio Code.

index.ts

// Cannot find name 'it'. Do you need to install type
// definitions for a test runner? Try 
// `npm i --save-dev @types/jest` or 
// `npm i --save-dev @types/mocha`. ts(2582)

describe('example', () => {
  it('adds two numbers together', () => {
    expect(2 + 2).toBe(4);
  });
});

Install the type definitions for Jest by running the following command in a terminal at the root directory of your project:

npm i -D @types/jest

If you didn’t already have Jest installed, you can install it with the type definitions in one command:

npm i -D @types/jest jest

Add typings to tsconfig.json types array

In some cases, this is all you need to do and the error will stop. But if it persists, you’ll need to add jest to the types array in your tsconfig.json file, so it looks something like this:

tsconfig.json

{
  "compilerOptions": {
    "types": [
      // ... other types
      "jest"
    ]
    // ..other settings
  }
}

Include test files

If the error still doesn’t go away, ensure that TypeScript does not ignore the directory containing your test files. If you’ve set the include array in your tsconfig.json file, ensure the patterns specified in this array match the directory where your test files are located.

For example, if your tests are located in a src directory, TypeScript will detect them with a configuration like this:

tsconfig.json

{
  "compilerOptions": {},
  "include": ["src/**/*"],
}

But if they’re located in a tests directory, we’ll need to add an additional glob pattern to make TypeScript detect them:

tsconfig.json

{
  "compilerOptions": {},
  "include": [
    "src/**/*",
    "tests/**/*"
  ],
}

We can also include glob patterns to match test files with a specific ending or extension. For example, we can include all files ending with “.spec.ts” and “.test.ts” with the following configuration:

tsconfig.json

{
  "compilerOptions": {},
  "include": [
    "src/**/*",
    "**/*.spec.ts",
    "**/*.test.ts"
  ],
}

Fix the Cannot Find Name ‘require’ Error in TypeScript

To fix the “cannot find name ‘require'” error in TypeScript, install the @types/node package into your project by running npm i -D @types/node.

This error can occur when you try to use the Node.js require() function in a TypeScript file.

The "cannot find name 'require' error in TypeScript.

You can fix it by running the following command in a terminal window at the root directory of your project:

npm i -D @types/node

If the error persists, try adding "node" to the types array in your tsconfig.json file:

tsconfig.json

{
  "compilerOptions": {
    "types": [
      // ... other types
      "node"
    ],
  },
}

Tip

If you’re just doing simple testing, you can quickly resolve this error by defining a require variable at the top of the TypeScript file:

declare var require: any;

[SOLVED] An Implementation Cannot Be Declared in Ambient Contexts Error in TypeScript

Are you experiencing the “an implementation cannot be declared in ambient contexts” error in TypeScript? This error can occur when you try to include logic in declaration files, for example:

car.d.ts

declare module 'car' {
  export class Car {
    color: string;
    maxSpeed: number;
    started: boolean;

    // Error: An implementation cannot be declared in ambient contexts
    start() {
      this.started = true;
    }
  }
}

Ambient declarations only exist in the type system and are erased at runtime, so they are not meant to contain implementations. The car module declaration in the example above is only meant to specify type information for a car module that is implemented somewhere else.

To fix this error, remove the implementation:

car.d.ts

declare module 'car' {
  export class Car {
    color: string;
    maxSpeed: number;
    started: boolean;

    start(); // implementation removed
  }
}

How to Fix the Cannot Use Namespace as a Type Error in TypeScript

Are you experiencing the “cannot use namespace as a type” error in TypeScript?

This error can occur when you try to import types declared as a module. For example:

car.d.ts

declare module 'car' {
  class Car {
    color: string;
    age: number;
    maxSpeed: number;
  }
}

index.ts


import Car from 'car';

// Cannot use namespace 'Car' as a type.
const user: Car = {
  color: 'red',
  age: 2,
  maxSpeed: 120,
};

To fix this error, use an export assignment to specify a default export for the namespace, like this:

car.d.ts

declare module 'car' {
  class Car {
    color: string;
    age: number;
    maxSpeed: number;
  }
  export = Car;
}