【问题标题】:Typescript cannot find name of own class when importing Node.js导入 Node.js 时,Typescript 找不到自己的类的名称
【发布时间】:2016-10-09 13:41:15
【问题描述】:

我正在尝试在我定义的类中使用 node.js 类(本例中为 net)。

Connection.ts:

import net = require('net');
class Connection  {

}

然后我在另一个文件中引用我的类,

ConnectionContext.ts:

interface IConnectionContext {
    connection: Connection;
}

当我有这段代码时,我在 ConnectionContext 中看到一个带下划线的“连接”,上面写着"IConnectionContext.ts(3,17): error TS2304: Cannot find name 'Connection'"

如果我从部件中删除 import * as net,编译错误就会消失。

我有点困惑,当我查看生成的 JavaScript 时,我所有的类在创建时看起来都一样。我不确定为什么 typescript 说这个类不存在。

这是我的 tsconfig:

{
    "compileOnSave": true,
    "compilerOptions": {
        "module": "commonjs",
        "outDir": "bin/",
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "moduleResolution": "node",
        "target": "es5"
    },
    "exclude": [
        "node_modules"
    ]
}

基于此,我需要做什么才能让我的界面看到我使用 node.js 模块的类?

【问题讨论】:

  • 对 typescript 不太熟悉,但如果它使用的是 es2015 模块规范,那么您似乎将节点样式模块与新模块语法混合在一起:import net = require('net');。你试过import net from 'net';吗?

标签: javascript node.js typescript typescript1.8


【解决方案1】:

如果我从部件中删除 import * as net,编译错误就会消失。

在没有importexport 语句的情况下,该文件被视为全局。一旦您导入/导出,它就会成为一个模块,因此必须导入。

这里有介绍:https://basarat.gitbooks.io/typescript/content/docs/project/modules.html?

【讨论】:

  • 这有点烦人,必须导入我使用的每个外部类。我的意思是,与我最初使用 node.js 的方式没有太大区别,这是有道理的。还是有点烦哈哈。
  • 如果您有路径拼写错误,您现在会收到编译器错误。在 js + node 中你可能会遇到运行时错误
  • 对,为了让它以当前的形式工作,我必须从'./Connection.ts'导入{Connection};这有点烦人,但从纯粹的 node.js 方面来看是有道理的。
猜你喜欢
  • 2020-11-18
  • 2019-02-20
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 2016-11-05
  • 2018-08-29
  • 1970-01-01
  • 2016-01-24
相关资源
最近更新 更多