[TypeScript] Create a fluent API using TypeScript classes
You can create an easy to chain API using TypeScript classes. Learn about the this
return type annotation and how it plays with function chaining and class inheritance.
class Adder { protected acc: number = 0; add(num: number): Adder { this.acc += num; return this; // enable to chain methods } get result() { return this.acc; } } const adder = new Adder() const res = adder.add(1).add(2).result; console.log(res); // 3 class Calculator extends Adder { subtract(num: number): Calculator { this.acc -= num; return this; } } const cal = new Calculator(); const res2 = cal.add(1).add(2).subtract(100).result; console.log(res2) // -97
You can also do:
const res2 = new Calculator() .add(1) .add(2) .subtract(100) .result; console.log(res2) // -97