I was testing out method chaining and found that it can be accomplished using "this" as a return type?
Here's 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);
Example in playground
Is this the correct way of achieving method chaining when mixing base and inherited classes?
To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.
Use the ReturnType utility type to get the return type of a function in TypeScript, e.g. type T = ReturnType<typeof myFunction> . The ReturnType utility type constructs a type that consists of the return type of the provided function type.
Introduction. One of the most important concepts to grasp in TypeScript is the use of the "this" keyword, which is used in object methods. The "this" keyword always points to the object that is calling a particular method.
Set the return type of an arrow function in TypeScript # You can set the return type of an arrow function in TypeScript right after its parameters, e.g. const greet = (name: string): string => {} . Once a function's return type is set, the type checker alerts us if the function returns a value of a different type.
Surely, using polymorphic this
makes fluent api's very easy to express as any subtypes 'flow' with the this
type. Check the Advanced Types section, and F-bounded polymorphism
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With