Skip to content

Widening and contextual typing

Relay keeps its routes in one table. A refactor moves { method: "GET", path: "/health" } out of the defineRoutes(...) call into a plain const, and method quietly becomes string. Nothing fails: the router still works. But the type that was "GET" | "POST" is gone, the typo method: "GTE" is no longer caught, and a handler that used to get a typed req now has an implicit any.

Two mechanisms decide this. Widening decides how specific the type of an expression stays when it is stored. Contextual typing decides what type an expression receives from the place it is written. M1 and M3 used both. This lesson states the rules.

A string literal expression has the type of that literal. What matters is what happens to the type once it is stored in a variable. A const keeps it. A mutable location (let, a property, an array element) widens it, because the value may be replaced later:

const c = "queued" // "queued"
let l = "queued" // string
const obj = { status: "queued", attempts: 0 } // { status: string; attempts: number }
const list = ["queued", "running"] // string[]

TypeScript calls the type of the bare expression "queued" a widening literal type. The const c declaration keeps the widening literal type, and when c is later copied into a mutable location, it widens at that point. A literal type that came from an annotation is a non-widening literal type and never widens:

const widening = "queued"
let a = widening // string
const annotated: "queued" = "queued"
let b = annotated // "queued"

Widening applies to inference results too. A type parameter’s candidate from a literal widens unless something says otherwise. Two things say otherwise: a constraint that includes a primitive type, and const:

declare function id<T>(value: T): T
declare function idString<T extends string>(value: T): T
const a = id("queued") // "queued": a const keeps the literal
let b = id("queued") // string: the let widens it
let c = idString("queued") // "queued": the constraint to string preserves the literal

The constraint rule is why <T extends string> keeps "queued" while <T> does not on let. A related effect: an object property whose constraint contains literal types keeps them without any as const:

declare function plain<T extends { status: string }>(value: T): T
declare function literal<T extends { status: "queued" | "done" }>(value: T): T
const p = plain({ status: "queued" }) // { status: string }
const l = literal({ status: "queued" }) // { status: "queued" }

The constraint is also a contextual type for the argument, and a literal given a contextual type that contains literal types is not widened.

Fixing the type at the declaration: as const and const T

Section titled “Fixing the type at the declaration: as const and const T”

as const marks the whole expression as non-widening: literals stay literal, objects become readonly, arrays become readonly tuples:

const route = { method: "GET", path: "/health" } as const
// { readonly method: "GET"; readonly path: "/health" }
const STATUSES = ["queued", "running", "done"] as const
type Status = (typeof STATUSES)[number] // "queued" | "running" | "done"

The const type parameter from M3 does the same for a call, so callers cannot forget. One consequence worth knowing: the type parameter’s constraint decides what shape is accepted, so it must allow readonly:

type Route = { method: "GET" | "POST"; path: string }
declare function defineRoutes<const T extends Record<string, Route>>(routes: T): T
const routes = defineRoutes({
health: { method: "GET", path: "/health" },
hook: { method: "POST", path: "/hooks/:source" },
})
type Paths = (typeof routes)[keyof typeof routes]["path"] // "/health" | "/hooks/:source"

Record<string, Route> accepts the readonly inferred object. For arrays you need readonly in the constraint (readonly string[]), since as const makes arrays readonly.

satisfies: check without widening or annotating

Section titled “satisfies: check without widening or annotating”

A type annotation does two things: it checks the value, and it replaces the inferred type with the annotation. A table annotated Record<string, Route> forgets which keys it has. satisfies (TypeScript 4.9) checks and keeps the inferred type:

type Route = { method: "GET" | "POST"; path: string }
const annotated: Record<string, Route> = {
health: { method: "GET", path: "/health" },
}
annotated.nothing // Route | undefined: no error, the key list is gone
const checked = {
health: { method: "GET", path: "/health" },
} satisfies Record<string, Route>
// @ts-expect-error: 'nothing' does not exist on the satisfied type
checked.nothing
checked.health.method // "GET"

satisfies also provides a contextual type, which is the second half of this lesson: the expression is typed as if it were assigned to that type, so literals stay literal where the target asks for them, and unannotated function parameters are typed:

type Job = { id: string; attempts: number }
const handlers = {
queued: (job) => job.id,
failed: (job) => job.attempts,
} satisfies Record<"queued" | "failed", (job: Job) => string | number>
handlers.queued({ id: "j1", attempts: 0 }) // (job: Job) => string

It does not change the value or add a cast, and the properties keep their own types: handlers.queued returns string, not string | number.

An expression has a contextual type when it is written somewhere that expects a type. The checker pushes that type down into the expression. This is the mechanism that gives parameters of callbacks their types, keeps literals literal, and types the elements of arrays:

type Job = { id: string; attempts: number }
declare const jobs: Job[]
jobs.map((job) => job.id) // argument position: job is Job
const onJob: (job: Job) => string = (job) => job.id // annotation: job is Job
function makeHandler(): (job: Job) => string {
return (job) => job.id // return position: job is Job
}
const tuples: [string, number][] = [["a", 1]] // array literal: inner arrays are tuples
const table: Record<string, (job: Job) => void> = { a: (job) => job.id.length }
const service: { run(job: Job): string } = { run(job) { return job.id } }

Contextual types flow in through: argument positions, annotations, return statements of annotated functions, object literal properties, array elements, satisfies, and conditional or logical operands (a ?? b, c ? x : y). They flow down through nested literals.

Contextual typing needs a type at the position, at the time the expression is checked. Lose either and parameters become implicit any, literals widen. The common causes:

type Job = { id: string; attempts: number }
// @ts-expect-error: parameter 'job' implicitly has an 'any' type
const byId = (job) => job.id
declare const jobs: Job[]
jobs.map(byId) // too late: the arrow was checked without a context
const table = {
// @ts-expect-error: no contextual type for 'job'
queued: (job) => job.id,
}

Extracting the callback to its own variable removes the position it was written in. The fix is to annotate the parameter, or annotate the variable, or put the expression back in position. A plain object with no annotation or satisfies gives no context either, which is what happened to the handlers table in the opening.

Overloads lose context in a subtler way. The checker tries overloads in order, and a function expression’s parameter types are fixed by the first candidate that assigns them:

declare function listen(handler: (code: number) => void): void
declare function listen(handler: (message: string) => void): void
listen((code) => code.toFixed()) // first overload matches
// @ts-expect-error: 'length' does not exist on 'number': the parameter was typed by the first overload
listen((message) => message.length)

Put the discriminating argument in the signature (on("a", f) with literal first argument works because the literal selects the overload before the callback is typed), or annotate the parameter.

A function expression with at least one unannotated parameter is context-sensitive: its parameter types come from outside, so it cannot be checked until the type parameters in its context are fixed. During inference the checker processes arguments in two phases. First it infers from every argument that is not context-sensitive, in any order. Then it fixes type parameters and checks the context-sensitive arguments left to right, each one contributing to the next:

declare function run<T>(produce: (n: number) => T, consume: (value: T) => void): void
run((n) => n + 1, (value) => value.toFixed()) // T = number, from the first callback
declare function runReversed<T>(consume: (value: T) => void, produce: (n: number) => T): void
// @ts-expect-error: 'value' is of type 'unknown': consume is checked before produce gave T a candidate
runReversed((value) => value.toFixed(), (n) => n + 1)

Both callbacks are context-sensitive, so source order decides. A callback with all parameters annotated is not context-sensitive and is inferred in the first phase, in either position:

declare function late<T>(consume: (value: T) => void, initial: T): T
late((value) => value.toFixed(), 1) // `initial` is not a function: T = number comes first

Lesson 4 applies this to object literals, where the properties are checked left to right since TypeScript 4.7.

Relay’s route table, status list and handler table have lost their literal types. Fix the declarations so the types survive and the handlers get their parameter types from context.

  • const keeps a literal type, mutable locations (let, properties, array elements) widen it. Literals from annotations never widen.
  • A constraint containing literal types, as const and const T all stop widening.
  • A type annotation replaces the inferred type, satisfies checks it and keeps it.
  • Contextual types flow into arguments, annotations, return statements, object properties and array elements. Moving a function out of its position drops the context.
  • Overloads fix an unannotated callback’s parameters from the first overload tried.
  • Context-sensitive arguments are deferred and checked left to right, so their order can matter.