Utility Type for curried functions in TypeScript
Aaron Reisman
Posted on June 12, 2023
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) => "";
💖 💪 🙅 🚩
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
webdev Breaking Away from JSON: A New Approach to Data Transport in Web Development
November 2, 2024