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); // 3class 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