无法找到名称“控制台”。这可能是什么原因?

下面的代码片段显示了 4号线处的一个输入脚本错误:

import {Message} from './class/message';


function sendPayload(payload : Object) : any{
let message = new Message(payload);
console.log(message);   // LINE 4
}

错误显示:

[ts] Cannot find name 'console'.

这是什么原因呢? 为什么它不能找到对象 console

60232 次浏览

You will have to install the @types/node to get the node typings, You can achieve that by executing the below command,

npm install @types/node --save-dev

Hope this helps!

Add "dom" in your lib section in compilerOptions in tsconfig.json.

Example:

{
"compilerOptions": {
"rootDir": "src",
"outDir": "bin",
"module": "commonjs",
"noImplicitAny": false,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"target": "es5",
"lib": [
"es6",
"dom"    <------- Add this "dom" here
],
"types": [
"reflect-metadata"
],
"moduleResolution": "node",
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}

There's a simpler, but hacky way to get console.log work: instead of console.log(message) write eval('console').log(message).

you can also use the same values as in @tBlabs answer from command line, and you don't need to install anything beside typescript:

tsc test.ts --lib esnext,dom

you separate values with comma and you don't need esnext for console.log to work.

I had the same problem in node terminal. Adding node to the types field of tsconfig.json solved my issue

Confirm that you don't import console from anything. like:

import { console } from 'console'; // Confirm you haven't a statement like this.

You can run npm install @types/node -D, and then you need to add types:[ 'node'] into your tsconfig.json also.

package.json

"devDependencies": {
"@types/node": "^15.0.3"
}

tsconfig.json

{
"compilerOptions": {
"composite": true,
"outDir": "./dist",
"rootDir": ".",
"declaration": true,
"noImplicitAny": true,
"esModuleInterop": true,
"module": "commonjs",
"target": "es6",
"types": [
"node"
],
"lib": [
"es6"
]
},
"exclude": [
"node_modules",
"dist"
]
}

just add ES6 and DOM in your tsconfig.json file

"lib": ["ES6", "DOM"]

It seems you are using typescript so here are the steps you need to do.

  1. Install global tsc using
npm I typescript --global
  1. call tsc --init if you don't have a tsconfig.json already in your folder

  2. If you have a tsconfig.json in the lib consider including DOM like this

 "lib": ["DOM" ...],