【问题标题】:How do I reference another module in typescript?如何在打字稿中引用另一个模块?
【发布时间】:2018-06-18 23:36:11
【问题描述】:

我在 typescript 2.4.1 中遇到了 importmodule 的问题。我有两个文件:

testAdd.ts:

module mymodule {
    export class myClassAdd {
        static add(left: number, right: number): number {
            return left + right;
        }
    }
}

testCallAdd.ts:

//import 'someLibrary';

module mymodule {
    export class myClassCallAdd {
        static callAdd(): void {
            let result: number = mymodule.myClassAdd.add(3, 4); //error here
        }
    }
}

这个代码现在编译得很好。我发现如果我尝试使用 import 关键字导入一些库,我就会开始出错。在testCallAdd.ts 中,如果我取消注释第一行的导入,我会收到一条错误消息,提示 myClassAdd 在 typeof mymodule 类型上不存在

我不明白为什么会收到此错误或如何修复它。 import 语句似乎正在做一些事情来阻止编译器看到testAdd.ts。有人能解释一下出了什么问题以及如何解决吗?

这是因为我有一个可以正常工作的 Angular 网站,但我想使用 jasmine 对其进行测试。我不知道如何设置它,以便角度块和单元测试都可以访问代码。

【问题讨论】:

  • @jpaugh,我在我的问题中以粗体显示错误,“myClassAdd 在类型 typeof mymodule 上不存在”

标签: angularjs typescript jasmine typescript2.4


【解决方案1】:

对于您的情况,您需要使用三斜杠指令:/// <reference types="somelibrary" />

见:http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html

但是,最好使用模块系统,而不是命名空间(这是您正在做的)。

您可以在此处了解有关模块和命名空间的更多信息: http://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html

如果您确实打算使用命名空间,因为 TypeScript 1.5 语法 module mymodule { ... } 已被弃用并被 namespace mymodule { ... } 取代

http://www.typescriptlang.org/docs/handbook/namespaces.html https://github.com/unional/typescript-guidelines/blob/master/pages/default/namespaces-and-modules.md

【讨论】:

  • 几个问题:(1) 当我使用/// <reference lib="jasmine" /> 时,我收到一条错误消息,提示“TS1084 无效引用指令语法”。 (2) 关于您随后的评论“更新的语法是命名空间 mymodule”,我对您的评论“使用模块系统,而不是命名空间”感到困惑。看起来您是在说“不要使用命名空间,而是使用命名空间”。我错过了什么吗?
  • 对不起,更新了答案,看看这样是否更清楚。
  • /// <ref 应该是 /// <reference types="..." />
猜你喜欢
  • 2015-05-09
  • 1970-01-01
  • 2017-10-26
  • 2013-02-25
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 2016-07-04
  • 1970-01-01
相关资源
最近更新 更多