Tweakr
    Preparing search index...

    Function partial

    • Creates a partially applied function by pre-filling some arguments, preserving the ability to use rest parameters and full TypeScript inference.

      Type Parameters

      • T extends (...args: any[]) => any
      • P extends any[]

      Parameters

      • fn: T

        The function to partially apply.

      • ...presetArgs: P

        Arguments to pre-fill for fn.

      Returns (...laterArgs: Tail<Parameters<T>, P>) => ReturnType<T>

      A new function that accepts the remaining arguments.

      const greet = (greeting: string, name: string, ...titles: string[]) =>
      `${greeting}, ${name}${titles.length ? " (" + titles.join(", ") + ")" : ""}!`;

      const sayHelloTo = partial(greet, "Hello");
      sayHelloTo("Alice", "PhD", "Professor"); // "Hello, Alice (PhD, Professor)!"

      // Works with multiple chained partials
      const add = (a: number, b: number, c: number, d: number) => a + b + c + d;
      const step1 = partial(add, 1);
      const step2 = partial(step1, 2);
      const step3 = partial(step2, 3);
      console.log(step3(4)); // 10

      1.2.0