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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42105984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:14:45  来源:igfitidea点击:

Cannot find name 'console'. What could be the reason for this?

javascriptnode.jstypescript

提问by helloJSON

The following snippet shows a typescript error at LINE 4:

以下代码段显示了第4 行的打字稿错误:

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

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

The error says:

错误说:

[ts] Cannot find name 'console'.

What could be the reason for this? Why it cannot find the object console?

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

回答by David R

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

您必须安装@types/node以获取节点类型,您可以通过执行以下命令来实现,

npm install @types/node --save-dev

Hope this helps!

希望这可以帮助!

回答by tBlabs

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

在 tsconfig.json 的 compilerOptions 的 lib 部分中添加“dom”。

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
    }
}

回答by jcubic

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

您还可以从命令行使用与@tBlabs 答案中相同的值,并且除了打字稿之外,您不需要安装任何东西:

tsc test.ts --lib esnext,dom

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

你用逗号分隔值,你不需要 esnext 来让 console.log 工作。

回答by Mahdi Sadeghi

I had the same problem in node terminal. Adding nodeto the typesfield of tsconfig.jsonsolved my issue

我在节点终端中遇到了同样的问题。添加node到解决我的问题的types领域tsconfig.json

回答by Yevhen Pavliuk

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

有一种更简单但很笨拙的console.log工作方式:而不是console.log(message)write eval('console').log(message)