How to Fix the “Cannot find name ‘console'” Error in TypeScript

The “cannot find name ‘console'” error occurs when you try to access the global console object in a TypeScript file. To fix it, install the @types/node NPM package for Node.js environments, or add 'DOM' to the lib array in your tsconfig.json for browser environments.

The "cannot find name 'console'" TypeScript error occuring in VSCode.
The “cannot find name ‘console'” TypeScript error occuring in VSCode.
index.ts
/* * Cannot find name 'console'. Do you need to change your * target library? Try changing the 'lib' compiler option * to include 'dom'.ts(2584) */ console.log('coding beauty');

Install Node.js typings

If your code is running in a Node.js environment, you can fix the “cannot find name ‘console'” error by running the following command at the root of your project directory.

Shell
npm i -D @types/node # Yarn yarn add --dev @types/node

This should resolve the error for Node.js runtimes.

Add typings to types array in tsconfig.json

In some cases, this is all you need to fix the error. But if it persists, you might need to add the newly installed typings to the types array of your tsconfig.json file.

Including 'node' string in the tsconfig.json types array will make the Node.js typings visible to the TypeScript compiler.

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

Add 'DOM' to lib array in tsconfig.json file

If your code is running in a browser, trying adding a 'DOM' string to the lib array in your tsconfig.json file.

tsconfig.json
{ "compilerOptions": { "lib": [ // other libs... "ES6", "DOM" ], // other settings... }, }

Doing this tells TypeScript that your code is client-side code, and it should provide a set of type definitions for built-in JavaScript APIs found in browser environments.

Restart code editor

If the error persists after trying out all these solutions, restarting your IDE or code editor might help.

Conclusion

To fix the “cannot find name ‘console’ error” in TypeScript, install Node typings if your code runs in Node.js, or add the 'DOM' string to your types array in your tsconfig.json if running in a browser.



Leave a Comment

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