During my experimentation with method chaining, I discovered that it is possible to use "this" as a return type. How interesting!
Let's take a look at an example:
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);
Check out the example on the playground
Could this be the right approach for achieving method chaining when dealing with base and inherited classes?