2016-05-23 8 views
2

私はメソッド連鎖をテストしていましたが、 "this"を戻り値の型として使用することができますか?"This"はTypeScriptの戻り値の型として使用されますか?

はここに例を示します

class Shape { 
    color: String; 

    setColor(value: string): this { //Shape won't chain 
     this.color = value; 
     return this; 
    } 
} 

class Square extends Shape { 
    width: number; 

    setWidth(value: number): Square { 
     this.width = value; 
     return this; 
    } 
} 

function drawSquare(square: Square) { 
    alert("width: " + square.width + "\ncolor: " + square.color); 
} 

let rect = new Square().setWidth(20).setColor("blue"); 
drawSquare(rect); 

Example in playground

が、これは、ベースと継承されたクラスを混合する際、メソッドチェーンを達成するための正しい方法は何ですか?

答えて

1

確かに、多型thisを使用すると、thisタイプの任意のサブタイプ 'フロー'として流暢なapiを非常に簡単に表現できます。 Advanced TypesセクションとF-bounded polymorphismセクションを確認してください。

+0

今、私はそれが何と呼ばれているのか知っています。早速のご返事ありがとうございます! –

関連する問題