&引用;这";在TypeScript中用作返回类型?

&引用;这";在TypeScript中用作返回类型?,typescript,Typescript,我正在测试方法链接,发现它可以使用“this”作为返回类型来完成 下面是一个例子: class Shape { color: String; setColor(value: string): this { //Shape won't chain this.color = value; return this; } } class Square extends Shape { width: number; setWidt

我正在测试方法链接,发现它可以使用“this”作为返回类型来完成

下面是一个例子:

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);


当混合基本类和继承类时,这是实现方法链接的正确方法吗?

当然,使用多态
this
可以很容易地将fluent api表示为具有
this
类型的任何子类型的“流”。检查该部分,然后
F-bounded多态性