2016-05-23 52 views
2

我正在測試方法鏈,並發現它可以使用「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使流利的api很容易表達爲this類型的任何子類型的「流」。檢查Advanced Types部分和F-bounded polymorphism

+0

現在我知道它叫什麼了。感謝您及時的回覆! –

相關問題