TypeScript のコンストラクタオーバーロード 質問する

TypeScript のコンストラクタオーバーロード 質問する

TypeScript でコンストラクタのオーバーロードを行った人はいますか。言語仕様 (v 0.8) の 64 ページにコンストラクタのオーバーロードについての説明がありますが、サンプル コードは示されていません。

私は今、非常に基本的なクラス宣言を試しています。次のようになります。

interface IBox {    
    x : number;
    y : number;
    height : number;
    width : number;
}

class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor(obj: IBox) {    
        this.x = obj.x;
        this.y = obj.y;
        this.height = obj.height;
        this.width = obj.width;
    }   

    constructor() {
        this.x = 0;
        this.y = 0;
        this.width = 0;
        this.height = 0;
    }
}

tsc BoxSample.ts で実行すると、重複したコンストラクタ定義がスローされます。これは明らかです。ご協力いただければ幸いです。

ベストアンサー1

TypeScript ではオーバーロードを宣言できますが、実装は 1 つしか持てず、その実装はすべてのオーバーロードと互換性のあるシグネチャを持たなければなりません。あなたの例では、これは次のようにオプションのパラメータで簡単に実行できます。

interface IBox {    
    x: number;
    y: number;
    height: number;
    width: number;
}
    
class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor(obj?: IBox) {    
        this.x = obj?.x ?? 0;
        this.y = obj?.y ?? 0;
        this.height = obj?.height ?? 0;
        this.width = obj?.width ?? 0;
    }   
}

または、より一般的なコンストラクタを持つ2つのオーバーロード。

interface IBox {    
    x: number;
    y: number;
    height: number;
    width: number;
}
    
class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor();
    constructor(obj: IBox); 
    constructor(obj?: IBox) {    
        this.x = obj?.x ?? 0;
        this.y = obj?.y ?? 0;
        this.height = obj?.height ?? 0;
        this.width = obj?.width ?? 0;
    }   
}

見る遊び場

おすすめ記事