导入外部定义

Bar*_*ast 9 typescript typescript1.4

使用Typescript,有没有办法从外部模块导入类型?

基本上我只是想让一个模块知道另一个模块(为Intellisense供电),但是没有在JavaScript中发出导入.我想这样做是因为有问题的模块可能已加载或未加载 - 即没有硬依赖,但我希望有一些运行的类型代码并使用该模块(如果它存在).

希望这很清楚.

Fen*_*ton 8

您可以使用定义文件以及引用注释,这使得类型可用而不添加任何import语句(例如requiredefine).

///<reference path="module.d.ts" />
Run Code Online (Sandbox Code Playgroud)

您可以在编译期间自动生成定义文件,但是出于您的目的,您可能想要手动设置自定义文件(取决于您希望如何使用它 - 预期会自动导入).

示例代码

ModuleA.ts

class ExampleOne {
    doSomething() {
        return 5;
    }
}

export = ExampleOne;
Run Code Online (Sandbox Code Playgroud)

ModuleB.ts

class ExampleTwo {
    doSomething() {
        return 'str';
    }
}

export = ExampleTwo;
Run Code Online (Sandbox Code Playgroud)

有可能的使用:

import B = require('moduleb');

var a = new ExampleOne();
var b = new B();
Run Code Online (Sandbox Code Playgroud)

要使这项工作,您将创建ModuleA.d.ts:

ModuleA.d.ts

declare class ExampleOne {
    doSomething(): number;
}
Run Code Online (Sandbox Code Playgroud)

然后像这样引用它:

/// <reference path="modulea.d.ts" />

import B = require('moduleb');

var a = new ExampleOne();
var b = new B();
Run Code Online (Sandbox Code Playgroud)