打字稿功能链怎么办?

时间:2018-12-29 23:39:46

标签: javascript function typescript

我想在 typescript 中使用函数链接。

考虑课程

export class numbOp(){
  private n;
  constructor(int num){
    this.n = num;
  }

  public add(inc = 1){
    this.n = this.n + inc;
  }

}

如何将其用作(1)

let finalNumber = new numbOp(3);
console.log(finalNumber) // Output: 3

如何将其用作(2)

let finalNumber = new numbOp(3).add();
console.log(finalNumber) // Output: 4

如何将其用作(3)

let finalNumber = new numbOp(3).add().add();
console.log(finalNumber) // Output: 5

如何将其用作(4)

let finalNumber = new numbOp(3).add().add(2).toString();
console.log(finalNumber) // Output: "6"
  

请帮我实现这一目标。在此先感谢:)

1 个答案:

答案 0 :(得分:6)

您只需要从要链接的函数中返回this

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"

修改

由于注释中的console.log部分似乎比链部分更有趣,因此,我将添加一些方法来确保控制台中的输出为数字:

  1. 覆盖toString并使用字符串强制获取对象的字符串表示形式
  2. 要求在显示之前调用终止符方法(即,在完成链接时不要忘记调用toString
  3. 覆盖valueOf并使用一元+运算符(这还将使您的类可用于二进制操作

最后一个选项的代码:

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