I'm a big fan of conditional queries in Laravel when using Eloquent. It makes code very readable and allows a nice builder pattern to construct an action.

Today, I wanted to do something similar in TypeScript.

The when function takes two parameters:

  • A condition (boolean) that determines whether the function executes.
  • A callback that receives the instance (this) and performs an operation.

Here's how I implemented it:

class MyClass {
  value: number;

  constructor(value: number) {
    this.value = value;
  }

  // Executes the callback only if the condition is true
  when(condition: boolean, fn: (instance: this) => void): this => {
    if (condition) {
      fn(this);
    }
    return this;
  }

  increment(): this {
    this.value++;
    return this;
  }

  multiply(factor: number): this {
    this.value *= factor;
    return this;
  }
}

Using the when function, you can write cleaner and more readable conditional logic:

const instance = new MyClass(5)
  .when(true, (self) => self.increment())  // Executes increment()
  .when(false, (self) => self.multiply(2)) // Skips multiply(2)
  .when(true, (self) => self.multiply(3)); // Executes multiply(3)

console.log(instance.value); // Output: 18 (5 + 1 = 6, then 6 * 3 = 18)

Why would you use the when Function?

  • Eliminates repetitive if statements.
  • Supports method chaining for a cleaner API.
  • Keeps your class methods concise and focused.