内部モジュール:
- typescritp ファイル内でモジュールを定義できます。
- モジュール内で定義されたすべての変数は、モジュールにスコープされ、グローバル スコープから削除されます。
- typescript ファイルをコンパイルすると、モジュールは名前空間のようなオブジェクトを形成するために必要に応じてネストする変数に変換されます。モジュール内で定義されたクラスは、IIFE (Immediately Invoked Function Expression) を使用してきちんと分離されていることに注意してください。
- 以下のコードは、MyClass 変数のスコープが MyInternalModule モジュールであることを示しています。モジュールの外部からアクセスすることはできないため、コードの最終行に MyClass という名前が見つからないというエラーが表示されます。
- export キーワードを使用して、モジュール外の変数にアクセスできます。
- 内部モジュールを拡張し、ファイル間で共有し、トリプル スラッシュ構文を使用して参照することもできます。( /// )
例:
module MyInternalModule{
class MyClass{ //if We write export keyword before the MyClass then last line works fine
constructor (
public height: number,
public width: number) {
}
}
//working properly
var obj1 = new MyClass(10, 4);
}
// it wont work //Because the out of the scope
var obj2 = new MyInternalModule.MyClass(10,4) //shows error: can not find name MyClass
Typescript のコンパイル済みバージョン:
var MyInternalModule;
(function (MyInternalModule) {
var MyClass = (function () {
function MyClass(height, width) {
this.height = height;
this.width = width;
}
return MyClass;
})();
//working properly
var obj1 = new MyClass(10, 4);
})(MyInternalModule || (MyInternalModule = {}));
外部モジュール:
例:
// bootstrapper.ts file
// imports the greeter.ts file as the greeter module
import gt = module('greeter');
export function run() {
var el = document.getElementById('content');
var greeter = new gt.Greeter(el);
greeter.start();
}
// greeter.ts file
// exports the entire module
export class Greeter {
start() {
this.timerToken = setInterval(() =>
this.span.innerText =
new Date().toUTCString(), 500);
}
}