Fluent APIs

Now that you're familiar with classes, we can present a very useful idiom called fluent APIs. Using a fluent API feels natural because it allows you to chain method calls without having to create intermediary variables.

Fluent APIs are often used with the builder design pattern, where you configure an object to create by calling different methods one after another, before triggering the effective construction using a build() method.

Here's an example to make this clear:

class Calculator { 
    constructor(private _currentValue: number = 0) { } 

    add(a: number): this { 
        this._currentValue += a; 
        return this; 
    } 

    substract(a: number): this { 
        this._currentValue -= a; 
        return this; 
    } 

    multiply(a: number): this { 
        this._currentValue *= a; 
        return this; 
    } 

    divide(a: number): this { 
        this._currentValue /= a; 
        return this; 
    } 

    get value(): number { 
        return this._currentValue; 
    } 
} 

let result: number = new Calculator(0) 
    .add(5) // returns this 
    .multiply(2) // returns this 
    .add(10) // we can keep chaining method calls 
    .divide(4) 
    .substract(2) 
    .value; // returns the value 

console.log(`Result: ${result}`); // 3 

In this example, we have re-implemented our calculator from Chapter 1Introduction to TypeScript and Preparing Your Development Environment, using a fluent API. As you can see, the principle is simply that each of the method calls returns this, thus, the class instance. This allows us to call other methods directly afterward. Finally, we retrieve the current value using the accessor.

When you return this, with a method, you actually use a feature of TypeScript called polymorphic this, which corresponds to the type or subtype of the containing class/interface. Another name for this feature is F-bounded polymorphism. You can, of course, still extend a class that uses this feature.

Building fluent APIs is great for code readability, and it should definitely be part of your arsenal.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.46.36