How To Solve “Cannot find name ‘console'” Error in TypeScript

While writing TypeScript code on the server side, you may get the error “Cannot find name ‘console‘”. The error is caused by the action that you accessing the console object in the global scope. This article will guide you to fix the error by installing type definitions for Node.js and making a few tweaks in the tsconfig.json file. Let’s get started.

The cause of the error “Cannot find name ‘console'” in TypeScript

The error occurs when you want to access the console object, but now NodeJS defines the console object in the global scope, and the TypeScript package uses lib.core.ts which has no console definition

Error Example:

const student: string = "John";

// Error occurs when we want to access the console object at global scope
console.log(student);

Error Output:

This error only appears when you access the console object in global scope

Cannot find name 'console'

In the above example, we use a very familiar command console.log() to print to the console the values contained in the variable for debugging purposes or to monitor the flow of data. However, since we are now accessing the console object in the global scope, the error occurs.

Solution for the error “Cannot find name ‘console'”

To fix this error you need to install type definitions for Node.js and add some settings to the tsconfig.json file.

Install type definitions for Node.js

You can fix this error by installing type definitions for NodeJS in case you use NodeJS to execute the program. You can use the below syntax:

npm i -D @types/node

if you use Yarn then run this command

yarn add --dev @types/node

Add node to types array

If you follow the above method and it still doesn’t work, try adding the node to the types array in the tsconfig.json file. Do this so that the TypeScript compiler understands NodeJS typings.

{
  "compilerOptions": {
    "types": ["node"]
  }
}

Add dom to lib array

If the above two methods still do not work, you can try to add dom to the lib array in the tsconfig.json file. This way, you implement TypeScript using the code on the client side, and it will provide the same methods available in the API as you work with the browser.

{
  "compilerOptions": {
    "lib": ["dom"]
  }
}

After performing the above steps, please restart the IDE for the changes to take effect.

Summary

So we have fixed the “Cannot find name ‘console‘” error in TypeScript in a few ways, like installing type definitions for Node.js and adding dom to lib array. You keep doing the above steps until your error is resolved. Thanks for reading. I hope the article is helpful to you.

Leave a Reply

Your email address will not be published. Required fields are marked *