Method Chaining in TypeScript

Method Chaining in TypeScript

In this post, we’re going to implement method chaining pattern using TypeScript.

What is method chaining?

Method chaining is a pattern which allows the developers to invoke multiple methods on the same instance of object. When used efficiently, this pattern makes the code a lot more readable.

If you write JavaScript for living, chances are you’ve already used method chaining in one way or another.

Here’s an example of method chaining in jQuery.

$("#card")
  .css('background', 'red')
  .width(400)
  .text('hello world!');

Implementing method chaining

Let’s start by building a Calculator class

class Calculator {
    private _value: number;
 
    constructor(value: number) {
        this._value = value;
    }
 
    add(num: number): Calculator {
        this._value = this._value + num;
        return this; 
    }
    subtract(num: number): Calculator {
        this._value = this._value - num;
        return this;
    }
    multiply(num: number): Calculator {
        this._value = this._value * num;
        return this;
    }
    divide(num: number): Calculator {
        this._value = this._value / num;
        return this;
    }
    result(): number {
        return this._value;
    }
}

As you can see, each method on the class returns this i.e the current instance of the object.

Now, lets create an object using out Calculator class and call it’s methods.

const calc = new Calculator(10);
console.log(
    calc.add(10)
        .multiply(5)
        .divide(10)
        .subtract(4)
        .result()
);

The above code will output 6 in the console.

That’s it! I hope you liked this post. If you’ve any query or feedback, feel free to drop a comment.

One thought on “Method Chaining in TypeScript”

Leave a Reply

Your email address will not be published. Required fields are marked *