Chaining commands/methods in Typescript

Chaining commands/methods in Typescript

Chaining methods is incredibly useful when simplifying complex object creation. Let's say we have a class/object that accepts quite a large number of constructor arguments. As you can see in the example below, we have two optional arguments called strength and health. We can create setter methods for those and return the context which allows as to chain commands. This makes the object creation more readable and also allows us to change those properties/values later on.

class Enemy {
    constructor(name: string, x: number, y: number, strength?: number, health?: number) {
        this.name = name;
        this.x = x;
        this.y = y;
        this.strength = strength;
        this.health = health;
    }
    
    setStrength(strength: number) {
        this.strength = strength;
        return this;
    }
    
    setHealth(health: number) {
        this.health = health;
        return this;
    }
}

const enemy = new Enemy("Goblin", 0, 0).setStrength(100).setHealth(100);