导入 TypeScript 模块 [英] Importing TypeScript modules
问题描述
我只是想了解一下 TypeScript,
I am just trying to get my head around TypeScript,
假设我有一个像这样的模块 animals.ts
:
Say I have a module animals.ts
like this:
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");
}
}
}
我想在另一个文件animals_panel.ts
中使用这个模块:
And I want to use this module in another file animals_panel.ts
:
import animals = require("animals")
module AnimalPanel {
var animal = new animals.Animals.Elephant();
animal.name();
}
- 我必须使用
animals.Animals.Elephant()
对我来说似乎有点奇怪,我本来希望Animals.Elephant()
.我做错了什么还是这是正确的行为? - 是否可以在
AnimalPanel
模块中导入import animal = require("animals")
(尝试执行此操作时出现错误)?
- It seems a bit weird to me that I have to use
animals.Animals.Elephant()
, I would have expectedAnimals.Elephant()
. Am I doing something wrong or is this the correct behaviour? - is it possible to import
import animals = require("animals")
inside theAnimalPanel
module (I get errors when I try to do this)?
推荐答案
当您使用外部模块时,每个文件都是一个模块.所以在文件中声明一个本地内部模块,例如export module Animals {
导致不必要的双重间接.
When you are using external modules each file is a module. So declaring a local internal module within a file e.g. export module Animals {
leads to unnecessary double indirection.
我会将animals.ts编码为:
I would code animals.ts as :
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");
}
}
然后将其用作:
import animals = require("animals")
module AnimalPanel {
var animal = new animals.Elephant();
animal.name();
}
PS:关于内部/外部打字稿模块这个主题的视频:http://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1
PS: a video on this subject of internal / external typescript modules : http://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1
这篇关于导入 TypeScript 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!