Utility Type for curried functions in TypeScript

lifeiscontent

Aaron Reisman

Posted on June 12, 2023

Utility Type for curried functions in TypeScript

Ever need a Type for a curried style function? Here's how you do it!

// Type helper to define curried function
type Func<T extends readonly any[]> = T["length"] extends 0
  ? () => void
  : T["length"] extends 1
  ? () => T[0]
  : (
      x: T[0]
    ) => T extends readonly [infer _, ...infer V]
      ? V["length"] extends 1
        ? V[0]
        : Func<V>
      : never;

// Usage
const func0: Func<[]> = () => undefined;
const func1: Func<[string]> = () => "";
const func2: Func<[string, number]> = (str) => 0;
const func3: Func<[number, boolean, string]> = (num) => (bool) => "";

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
lifeiscontent
Aaron Reisman

Posted on June 12, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related