// 文件名 : SomeInterface.ts
export interface SomeInterface {
// 代码部分
}
另一个文件中
import someInterfaceRef = require("./SomeInterface");
实例
// IShape.ts
/// <reference path = "IShape.ts" />
export interface IShape {
draw();
}
// Circle.ts
import shape = require("./IShape");
export class Circle implements shape.IShape {
public draw() {
console.log("Cirlce is drawn (external module)");
}
}
// Triangle.ts
import shape = require("./IShape");
export class Triangle implements shape.IShape {
public draw() {
console.log("Triangle is drawn (external module)");
}
}
// TestShape.ts
import shape = require("./IShape");
import circle = require("./Circle");
import triangle = require("./Triangle");
function drawAllShapes(shapeToDraw: shape.IShape) {
shapeToDraw.draw();
}
drawAllShapes(new circle.Circle());
drawAllShapes(new triangle.Triangle());
使用 tsc 命令编译以上代码(AMD):
tsc —module amd TestShape.ts
IShape.js 文件代码:
define(["require", "exports"], function (require, exports) {
});
Circle.js 文件代码:
define(["require", "exports"], function (require, exports) {
var Circle = (function () {
function Circle() {
}
Circle.prototype.draw = function () {
console.log("Cirlce is drawn (external module)");
};
return Circle;
})();
exports.Circle = Circle;
});
Triangle.js 文件代码:
define(["require", "exports"], function (require, exports) {
var Triangle = (function () {
function Triangle() {
}
Triangle.prototype.draw = function () {
console.log("Triangle is drawn (external module)");
};
return Triangle;
})();
exports.Triangle = Triangle;
});
TestShape.js 文件代码:
define(["require", "exports", "./Circle", "./Triangle"],
function (require, exports, circle, triangle) {
function drawAllShapes(shapeToDraw) {
shapeToDraw.draw();
}
drawAllShapes(new circle.Circle());
drawAllShapes(new triangle.Triangle());
});
使用 tsc 命令编译以上代码(Commonjs):
tsc —module commonjs TestShape.ts
得到以下 JavaScript 代码:
Circle.js 文件代码:
var Circle = (function () {
function Circle() {
}
Circle.prototype.draw = function () {
console.log("Cirlce is drawn");
};
return Circle;
})();
exports.Circle = Circle;
Triangle.js 文件代码:
var Triangle = (function () {
function Triangle() {
}
Triangle.prototype.draw = function () {
console.log("Triangle is drawn (external module)");
};
return Triangle;
})();
exports.Triangle = Triangle;
TestShape.js 文件代码:
var circle = require("./Circle");
var triangle = require("./Triangle");
function drawAllShapes(shapeToDraw) {
shapeToDraw.draw();
}
drawAllShapes(new circle.Circle());
drawAllShapes(new triangle.Triangle());
输出结果为:
Cirlce is drawn (external module)
Triangle is drawn (external module)