LoginSignup
39
32

More than 5 years have passed since last update.

TypeScript: コンストラクタのオーバーロード

Last updated at Posted at 2014-05-06

TypeScript でのコンストラクタのオーバーロードのサンプルです。

  • constructor キーワードが3回でてきてますが、最後の3つ目がコンストラクタの実体(定義)です。
  • 最初の2つ(セミコロンで終了している部分)がシグナチャとなります。
  • コンストラクタの実体(定義)では型の曖昧性がある引数については any で受けて instanceof などで実際の型を判別した上で処理を分岐させます。
app.ts
function writeln(msg: any) {
    console.log(msg);
    alert(msg);
}

class Vector2 {
    x: number;
    y: number;
    constructor(x: number, y: number);
    constructor(v: Vector2);
    constructor(a: any, b?: number) {
        // null, undefined が渡された場合
        if (a == null) {
            this.x = 0;
            this.y = 0;
            return;
        }
        // instanceof でどちらが呼ばれたのか判断
        if (a instanceof Vector2) {
            this.x = a.x;
            this.y = a.y;
        } else {
            this.x = a;
            this.y = b;
        }
    }
}

var v1 = new Vector2(0, 20);
var v2 = new Vector2(v1);
var v3 = new Vector2(null);
var v4 = new Vector2(undefined);

writeln(v1.x + ":" + v1.y);
writeln(v2.x + ":" + v2.y);
writeln(v3.x + ":" + v3.y);
writeln(v4.x + ":" + v4.y);

念のため、生成された JavaScript のコードを掲載します。

  • シグナチャは消えてなくなっています。
  • JavaScript ではもともと引数が省略可能なので、コンストラクタの実体(定義)は2引数を取る関数として記述されています。
app.js
function writeln(msg) {
    console.log(msg);
    alert(msg);
}

var Vector2 = (function () {
    function Vector2(a, b) {
        // null, undefined が渡された場合
        if (a == null) {
            this.x = 0;
            this.y = 0;
            return;
        }
        // instanceof でどちらが呼ばれたのか判断
        if (a instanceof Vector2) {
            this.x = a.x;
            this.y = a.y;
        } else {
            this.x = a;
            this.y = b;
        }
    }
    return Vector2;
})();

var v1 = new Vector2(0, 20);
var v2 = new Vector2(v1);
var v3 = new Vector2(null);
var v4 = new Vector2(undefined);

writeln(v1.x + ":" + v1.y);
writeln(v2.x + ":" + v2.y);
writeln(v3.x + ":" + v3.y);
writeln(v4.x + ":" + v4.y);
//# sourceMappingURL=app.js.map

参考

39
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
32