I want to use function chaining in typescript.
Consider a class
export class numbOp(){
private n;
constructor(int num){
this.n = num;
}
public add(inc = 1){
this.n = this.n + inc;
}
}
How do I use it as (1)
let finalNumber = new numbOp(3);
console.log(finalNumber) // Output: 3
How do I use it as (2)
let finalNumber = new numbOp(3).add();
console.log(finalNumber) // Output: 4
How do I use it as (3)
let finalNumber = new numbOp(3).add().add();
console.log(finalNumber) // Output: 5
How do I use it as (4)
let finalNumber = new numbOp(3).add().add(2).toString();
console.log(finalNumber) // Output: "6"
Please, help me out to achieve this. Thanks in advance :)
In TypeScript, optional chaining is defined as the ability to immediately stop running an expression if a part of it evaluates to either null or undefined .
Method Chaining is the practice of calling different methods in a single line instead of calling other methods with the same object reference separately. Under this procedure, we have to write the object reference once and then call the methods by separating them with a (dot.).
You just need to return this
from the functions you want to chain
class numbOp {
private n: number;
constructor(num: number) {
this.n = num;
}
public add(inc = 1) : this { // annotation not necessary added to address comments
this.n = this.n + inc;
return this;
}
toString() {
return this.n;
}
}
let finalNumber = new numbOp(3);
console.log(finalNumber + "") // Output: 3
//How do I use it as (2)
let finalNumber2 = new numbOp(3).add();
console.log(finalNumber2 + "") // Output: 4
//How do I use it as (3)
let finalNumber3 = new numbOp(3).add().add();
console.log(finalNumber3 + "") // Output: 5
//How do I use it as (4)
let finalNumber4 = new numbOp(3).add().add(2).toString();
console.log(finalNumber4) // Output: "6"
Edit
Since the console.log
part seems to have become more interesting then the chain part in the comments, I'll add the ways to ensure the output in the console is a number:
toString
and use string coercion to get the string representation of the objecttoString
when you finish the chain)valueOf
and use the unary +
operator (this will also make you class usable in binary operationsCode for last option:
class numbOp {
private n: number;
constructor(num: number) {
this.n = num;
}
public add(inc = 1) : this { // annotation not necessary added to address comments
this.n = this.n + inc;
return this;
}
valueOf() {
return this.n;
}
}
let finalNumber2 = new numbOp(3).add();
console.log(+finalNumber2) // Output: 4
console.log(1 + (+finalNumber2)) // Output: 5
console.log(1+(finalNumber2 as any as number)) // Output: 5
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