zoukankan      html  css  js  c++  java
  • [TypeScript] Create a fluent API using TypeScript classes

    You can create an easy to chain API using TypeScript classes. Learn about the thisreturn 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
  • 相关阅读:
    安全
    请求
    使用 Fetch
    安全
    script
    PWA
    link(外部资源关系)
    base(根URL)
    缓存
    IndexedDB基本概念
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6523777.html
Copyright © 2011-2022 走看看