Skip to content

Inference: candidates, priorities and overloads

Relay’s defineJob({ handle, parse }) takes a parser and a handler. Written one way round, the handler’s payload is the parser’s return type. Written the other way round, payload is unknown and every property access is an error. Same function, same arguments, different order. Elsewhere pickFirst(queuedJob, draft) returns a Draft and silently drops id, because a supertype was a valid answer and nothing said otherwise.

Both come from how the checker fills in a type argument you did not write. M3 and M4 showed what inference does. This lesson shows the procedure, so you can predict the result instead of trying calls until one compiles.

For each call, the checker walks every argument against its parameter type. Wherever it finds a type parameter on the target side, it records a candidate: the part of the argument’s type that lines up. A call usually collects several candidates per parameter. Then it picks one answer per type parameter. What happens depends on where the candidates came from.

Covariant candidates (from values: arguments, return types of callbacks) are combined by taking the common supertype: the first candidate that every other candidate is assignable to. If there is none, the leftmost candidate wins and the other arguments become errors. There is no automatic union:

declare function two<T>(a: T, b: T): T
class Draft { name = "draft" }
class Job extends Draft { id = "j1" }
class Email extends Draft { to = "a@b.c" }
const widest = two(new Job(), new Draft()) // Draft: the supertype of both
const same = two(new Draft(), new Job()) // Draft: order does not matter here
// @ts-expect-error: neither Job nor Email is a supertype of the other: the first one wins
two(new Job(), new Email())

That is the pickFirst(queuedJob, draft) bug: Draft is a perfectly good T.

Literals are the exception. Candidates that are literals of the same primitive type are combined into a union, and a T at the top level of the return type keeps them, unless the type parameter has no constraint and the result is stored in a mutable location:

declare function two<T>(a: T, b: T): T
declare function wrapped<T>(a: T, b: T): { value: T }
const a = two(1, 2) // 1 | 2
const b = wrapped(1, 2) // { value: number }: T is not at the top level of the return type
// @ts-expect-error: 1 and "a" are literals of different primitives: first candidate wins
two(1, "a")

Fresh object literals and array literals are the other exception. When every candidate is a fresh literal, the checker unions them, after normalizing the object shapes:

declare function wrapped<T>(a: T, b: T): { value: T }
const objects = wrapped({ a: 1 }, { b: 2 })
// { value: { a: number; b?: never } | { a?: never; b: number } }
const arrays = wrapped([1], ["a"]) // { value: number[] | string[] }
declare const left: { kind: "a" }
declare const right: { kind: "b" }
// @ts-expect-error: values with declared types are not literals: no union, first candidate wins
wrapped(left, right)

A candidate found in a parameter position of a callback is contravariant. Two callbacks that each consume T put two contravariant candidates on it. The checker takes the common subtype, the one candidate every other candidate accepts as input, and it must be assignable to what each callback needs:

declare function both<T>(f: (x: T) => void, g: (x: T) => void): T
declare const onA: (x: { a: number }) => void
declare const onAB: (x: { a: number; b: number }) => void
declare const onB: (x: { b: number }) => void
const t = both(onA, onAB) // { a: number; b: number }: the subtype both callbacks can accept
// @ts-expect-error: no candidate is a subtype of the other: the first wins and the second callback fails
both(onA, onB)

Not all candidates are equal. Each one carries a priority, and the checker keeps only the candidates with the best priority for each type parameter. A direct match (the argument is a T) is better than a match through a union, a mapped type or a return type. The effect shows when one parameter type offers two ways to read the same argument:

declare function normalize<T>(input: T | T[]): T[]
const one = normalize("a") // string[]
const many = normalize(["a", "b"]) // string[]: matched against T[], not against naked T

["a", "b"] could be a T (making the result string[][]) or a T[]. A naked type parameter in a union has a lower priority than a direct match, so the array match wins when it applies. This is why normalize-style APIs work at all, and why the same signature written (input: T) gives string[][].

Return type inference has the lowest priority of all. When the call is in a position with an expected type, the checker infers from that expected type first, but only to seed the candidates: anything found in the arguments overrides it. Use it as a fallback for type parameters that have no argument to infer from:

declare function emptyList<T>(): T[]
const none = emptyList() // unknown[]: nothing to infer from
const strings: string[] = emptyList() // string[]: the expected type is the only candidate
declare function wrap<T>(value: T): T[]
const names: ("a" | "b")[] = wrap("a") // T = "a": the expected type keeps the literal, the argument decides T
const plain = wrap("a") // string[]

Lesson 2 showed that unannotated function arguments are deferred until the type parameters they depend on are fixed. Since TypeScript 4.7 the same left-to-right rule also applies inside one object literal. Each context-sensitive property can use candidates from the properties before it:

declare function defineJob<P, R>(job: {
parse: (raw: unknown) => P
handle: (payload: P) => R
}): [P, R]
const ok = defineJob({
parse: (raw) => ({ to: String(raw) }),
handle: (payload) => payload.to.length, // payload: { to: string }
})
const wrong = defineJob({
// @ts-expect-error: 'payload' is of type 'unknown': P has no candidate yet
handle: (payload) => payload.to.length,
parse: (raw) => ({ to: String(raw) }),
})

Both functions have an unannotated parameter, so both are context-sensitive and are processed in source order. When handle is checked first, P has no candidates, and it is fixed to unknown. Fixing is permanent for that call: parse later contributes a candidate that is too late. The type of the declaration does not matter, only the order at the call site.

Two ways to make order stop mattering. Annotate the parameter, which makes the function non-context-sensitive, so it is inferred in the first phase:

declare function defineJob<P, R>(job: {
parse: (raw: unknown) => P
handle: (payload: P) => R
}): [P, R]
const annotated = defineJob({
handle: (payload) => payload.to.length,
parse: (raw: unknown) => ({ to: String(raw) }),
})

Or design the signature so the producer comes first by position, which the exercise does: createJob(parse, handle).

When one argument must not contribute, NoInfer<T> removes its candidates (M4 has the full story). It also closes the supertype hole from the opening, because the second argument is now only checked:

declare function withFallback<T>(primary: T | undefined, fallback: NoInfer<T>): T
class Draft { name = "draft" }
class Job extends Draft { id = "j1" }
declare const job: Job
declare const other: Job
declare const draft: Draft
const ok = withFallback(job, other) // Job
// @ts-expect-error: 'Draft' is not assignable to 'Job'
withFallback(job, draft)

A call to an overloaded function is resolved top-down: the checker tries each signature in declaration order, and the first one whose parameters accept the arguments is chosen. Three consequences follow.

First, the implementation signature is not part of the type. Only the overload signatures above it are callable:

function toMillis(input: string): number
function toMillis(input: number): number
function toMillis(input: string | number): number {
return Number(input)
}
declare const input: string | number
// @ts-expect-error: no overload accepts 'string | number', even though the implementation does
toMillis(input)

Second, overloads do not distribute over unions. A union argument is tried against each signature as a whole, and neither accepts it. The fix is a signature that does:

function toMillis(input: string): number
function toMillis(input: number): number
function toMillis(input: string | number): number
function toMillis(input: string | number): number {
return Number(input)
}
declare const input: string | number
toMillis(input) // number

Third, order is the semantics. Put the most specific overload first, since a general one above it would always match. And overloads cannot infer across each other: each is checked on its own. When overloads exist only to relate an input type to an output type, one generic signature with a conditional return type usually serves callers better. It accepts unions and gets one error message, not “no overload matches”.

A default (<T = Job>) is used only when inference produces no candidates. It is not a fallback for a failed match, and it does not compete with candidates from arguments or from the return type:

declare function emptyQueue<T = string>(): T[]
declare function queueOf<T = string>(first?: T): T[]
const a = emptyQueue() // string[]: no candidates, so the default applies
const b = queueOf(1) // number[]: the argument is a candidate, the default is ignored
const c: number[] = emptyQueue() // number[]: the expected type is a candidate too

A default also does not constrain: queueOf<T = string> accepts 1 because T is inferred as number. If the default should restrict what callers may pass, put it in the constraint (T extends string) instead.

Relay’s job API infers the wrong types in four places: a handler that cannot see its parser’s output, a fallback that widens the result, an array that is wrapped twice, and an overload set that rejects a union. Fix the signatures. The tests contain Expect<Equal<...>> and @ts-expect-error checks plus runtime assertions.

  • Covariant candidates combine to the common supertype, or the first candidate when none is. Only same-primitive literals and fresh object or array literals are unioned.
  • Contravariant candidates combine to the common subtype.
  • A naked T inside a union has a lower priority than a direct match, and return-type inference is the lowest priority overall. Both are fallbacks.
  • Context-sensitive arguments are checked left to right, including properties of one object literal. A type parameter fixed too early stays fixed.
  • NoInfer turns an inference site into a check.
  • Overloads resolve top-down, hide the implementation signature, and do not distribute over unions.
  • A default applies only when there are no candidates.