Compose functions and arguments safely
Compose functions while preserving argument tuples and return types; write pipe/compose helpers that stay type-safe.
Intro
Goal: Compose functions without losing argument info. Variadic tuples let you keep the full args tuple through pipe/compose helpers.
- Preserve arity and names
- Keep inference across steps
- No
any, no casts
Basic compose
compose: The first function takes all arguments (...args: A), the second consumes its output; arity and types are preserved.
function compose<A extends any[], B, C>(g: (b: B) => C, f: (...args: A) => B) {
return (...args: A): C => g(f(...args))
}
function toLen(a: string, n: number) { return `${a}${n}`.length }
function isEven(x: number) { return x % 2 === 0 }
const c1 = compose(isEven, toLen)
const ok = c1("id", 99) // booleanAll lessons in this course
- Tuple rest elements, curry types
- Compose functions and arguments safely
- Strongly-typed builders