导入TypeScript模块

jax*_*jax 21 typescript

我只是试图了解TypeScript,

说我有这样一个模块animals.ts:

export module Animals {

    export interface Animal {
        name(): void;
    }

    export class Elephant implements Animal {

        constructor() {

        } 

        public name() {
            console.log("Elephant");
        }
    }

    export class Horse implements Animal {

        constructor() {

        }

        public name() {
            console.log("Horse");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想在另一个文件中使用此模块animals_panel.ts:

import animals = require("animals")

module AnimalPanel {

    var animal = new animals.Animals.Elephant();
    animal.name();
}
Run Code Online (Sandbox Code Playgroud)
  1. 这似乎有点不可思议,我认为我必须使用animals.Animals.Elephant(),我本来期望Animals.Elephant().我做错了什么或者这是正确的行为吗?
  2. 是否可以import animals = require("animals")AnimalPanel模块内导入(我尝试这样做时会出错)?

bas*_*rat 31

当您使用外部模块时,每个文件都是一个模块.因此,在文件中声明本地内部模块export module Animals {会导致不必要的双重间接.

我会将animals.ts编码为:

export interface Animal {
    name(): void;
}

export class Elephant implements Animal {

    constructor() {

    } 

    public name() {
        console.log("Elephant");
    }
}

export class Horse implements Animal {

    constructor() {

    }

    public name() {
        console.log("Horse");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将其用作:

import animals = require("animals")

module AnimalPanel {

    var animal = new animals.Elephant();
    animal.name();
}
Run Code Online (Sandbox Code Playgroud)

PS:关于此内部/外部打字稿模块主题的视频:http://www.youtube.com/watch?v = KDrWLMUY0R0&hd = 1

  • 我看到他们导入了一个模块(比如说NgModule),然后他们说了@NgModule({})。这是什么意思?我的意思是`@ NgModule`(非常感谢) (2认同)