Variadic tuple types
Relay’s handlers have different argument lists: (source, body) for a webhook, (jobId, attempt)
for a retry. Two helpers are needed for all of them. One fixes the first arguments, so
onGithub = partial(handleWebhook, "github"). The other adds a request context in front, for
logging. In M3’s higher-order lesson a helper like this took (...args: any[]), and the
types were lost.
A function’s parameters are a tuple type. Variadic tuple types let you spread one tuple inside another, so the helper can say “the first part, then the rest” and keep each element’s type.
Spreading tuples
Section titled “Spreading tuples”In a tuple type, ...T spreads another tuple type T in place:
type Concat<A extends readonly unknown[], B extends readonly unknown[]> = [...A, ...B]
type A = Concat<[string], [number, boolean]> // [string, number, boolean]type B = Concat<[], [number]> // [number]The constraint readonly unknown[] says “any tuple or array”. Without it, ...A is not allowed,
because the compiler needs to know A can be spread.
Taking a tuple apart
Section titled “Taking a tuple apart”infer works inside a tuple pattern, the same way it did for strings in
lesson 4:
type Tail<T extends readonly unknown[]> = T extends readonly [unknown, ...infer Rest] ? Rest : []type Head<T extends readonly unknown[]> = T extends readonly [infer First, ...unknown[]] ? First : never
type A = Tail<[string, number, boolean]> // [number, boolean]type B = Head<[string, number, boolean]> // stringtype C = Tail<[]> // []Tail of an empty tuple does not match the pattern, so the false branch gives [].
Labeled elements
Section titled “Labeled elements”Tuple elements can have names. They do not change the type, but editors show them in signature hints:
type WebhookArgs = [source: string, body: string]type RetryArgs = [jobId: string, attempt: number]
declare function dispatch(...args: WebhookArgs): voiddispatch("github", "{}")Hovering dispatch shows (source: string, body: string) instead of (args_0: string, args_1: string).
Use labels on any tuple that is a parameter list.
partial: fix the first arguments
Section titled “partial: fix the first arguments”partial(fn, ...first) should return a function that takes the rest of fn’s parameters. The
parameters are [...A, ...B], where A is what first provides and B is what remains:
function partial<A extends unknown[], B extends unknown[], R>( fn: (...args: [...A, ...B]) => R, ...first: A): (...rest: B) => R { return (...rest) => fn(...first, ...rest)}
const record = (source: string, attempt: number, retried: boolean): string => `${source}:${attempt}:${retried}`
const fromGithub = partial(record, "github")// (rest_0: number, rest_1: boolean) => string
fromGithub(2, true)// @ts-expect-error: attempt must be a numberfromGithub("2", true)// @ts-expect-error: the boolean is missingfromGithub(2)The compiler infers A from the extra arguments, ["github"], and then B is what is left of
fn’s parameters. This is the case where the old any[] version lost everything: nothing said
which arguments were fixed, so nothing could say which were left.
withContext: add a parameter
Section titled “withContext: add a parameter”The second helper wraps a handler so callers pass a context first. The context is used by a logging hook, and the handler itself does not see it:
function withContext<Ctx, Args extends unknown[], R>( fn: (...args: Args) => R, onCall: (ctx: Ctx) => void,): (ctx: Ctx, ...args: Args) => R { return (ctx, ...args) => { onCall(ctx) return fn(...args) }}
const queued = (jobId: string, attempt: number): number => jobId.length + attempt
const traced = withContext(queued, (ctx: { requestId: string }) => console.log(ctx.requestId))// (ctx: { requestId: string }, jobId: string, attempt: number) => number
traced({ requestId: "r1" }, "j1", 2)// @ts-expect-error: the context comes firsttraced("j1", 2)The return type (ctx: Ctx, ...args: Args) => R is [ctx: Ctx, ...Args] written in parameter
form. Each wrapped handler keeps its own argument list, so a bug that swaps jobId and attempt
is still a compile error.
Exercise
Section titled “Exercise”The starter’s Concat and Tail give unknown[], and partial and withContext accept
anything. Write the tuple types and the generic signatures so the tests’ inferred types match.
- A function’s parameters are a tuple.
[...A, ...B]joins two tuples and keeps every element’s type. - Spreading needs the constraint
readonly unknown[]. T extends readonly [unknown, ...infer Rest]takes a tuple apart, asinferdid for strings.partialsplitsfn’s parameters into[...A, ...B]. The extra arguments giveA, the result takesB.- A wrapper that adds a parameter returns
(ctx: Ctx, ...args: Args) => R. Label tuple elements so hovers stay readable.
Further reading
Section titled “Further reading”- TypeScript 4.0: where variadic tuple types came in.