Control-flow analysis and its limits
Relay’s event code is full of event as Failed and payload!.id. Each one was added because the
checker did not follow something the author could see. Some of those casts hid real bugs (a
payload! on an event that has no payload throws in production). Others were never needed: the
checker could follow the code if it had been written slightly differently. To tell the two apart you
need the model, not a list of tips.
M1 taught narrowing as a set of checks. This lesson explains the mechanism behind it, control-flow analysis, and where it stops.
The flow graph
Section titled “The flow graph”For each function the checker builds a graph of the places control can go: branches, loops,
return, throw, assignments and the points where conditions are tested. A variable’s type at a
reference is found by walking that graph backwards from the reference to its declaration,
combining what each path says. A branch condition contributes a narrowing, an assignment contributes
the assigned type, and paths that cannot reach the reference are dropped:
function size(value: string | number | undefined): number { if (value === undefined) throw new Error("missing") // this path ends here if (typeof value === "string") return value.length // string return value // number: the two paths above are gone}Two consequences. Narrowing depends on where you are in the graph, not on scopes: it follows
return, throw, break and continue, so an early exit narrows the rest of the function.
And an assignment narrows too, to the assigned type filtered by the declared type:
let value: string | number = "relay"value.length // string: the declared union was narrowed by the assignment
value = 1value.toFixed() // numbernever-returning calls
Section titled “never-returning calls”A call to a function that returns never ends the path, as throw does. But the checker decides
that from a syntactic shape, before types are fully known: the called name must have an explicit
type. A function declaration with a never return annotation qualifies. A const holding an
arrow function does not, even if it returns never:
function failNow(message: string): never { throw new Error(message)}
const failLater = (message: string): never => { throw new Error(message)}
function a(id: string | undefined): string { if (id === undefined) failNow("id is required") return id // string}
function b(id: string | undefined): string { if (id === undefined) failLater("id is required") // @ts-expect-error: 'id' is possibly 'undefined': the call is not recognized as unreachable return id}The same holds for assertion functions, which M1 covered: asserts x is T only works on a
reference whose declaration carries an explicit type, so a const assert = (...): asserts ...
arrow needs an annotation on the variable. The practical rule is to declare these helpers with
function:
const assertLater = (value: string | undefined): asserts value is string => { if (value === undefined) throw new Error("missing")}
const assertTyped: (value: string | undefined) => asserts value is string = (value) => { if (value === undefined) throw new Error("missing")}
function c(id: string | undefined) { // @ts-expect-error: assertions require every name in the call target to have an explicit type assertLater(id) assertTyped(id) return id.length}Aliased conditions
Section titled “Aliased conditions”Since TypeScript 4.4 a condition can be stored in a variable and tested later. The checker still
narrows, because it keeps the condition expression attached to the const:
type RelayEvent = | { kind: "job.queued"; id: string } | { kind: "job.failed"; id: string; error: string } | { kind: "ping" }
function describe(event: RelayEvent): string { const isFailed = event.kind === "job.failed" const hasId = event.kind !== "ping" if (isFailed) return event.error if (hasId) return event.id return "ping"}The rules are narrow:
- The alias must be a
constwith no type annotation. Alethas no stable meaning, since it can change between declaration and test, andconst a: boolean = x.kind === "job"does not narrow. - The reference being narrowed must be a
const, areadonlyproperty, or a parameter that is never assigned in the function. Ifeventis reassigned anywhere, the alias stops working. - Aliases chain, up to five levels (a cutoff set in TypeScript PR #44730).
The reassignment rule is checked over the whole function, not up to the test:
type Ev = { kind: "job"; id: string } | { kind: "ping" }
function reassigned(event: Ev) { const isJob = event.kind === "job" // @ts-expect-error: 'event' is assigned below, so the alias does not narrow it here if (isJob) event.id event = { kind: "ping" }}
declare const x: Evconst a1 = x.kind === "job"const a2 = a1const a3 = a2const a4 = a3const a5 = a4const a6 = a5if (a5) x.id // five levels: narrows// @ts-expect-error: six levels is one too manyif (a6) x.idDestructured discriminants
Section titled “Destructured discriminants”Destructuring a discriminated union keeps the relationship between the pieces when they are
declared with const (TypeScript 4.6). Narrowing the discriminant narrows the other destructured
variables, and it narrows the original object too, through the alias rule above:
type Result = | { kind: "ok"; value: number } | { kind: "error"; value: string; message: string }
function show(result: Result): string { const { kind, value } = result if (kind === "ok") return value.toFixed(1) return value.toUpperCase() + result.message}
function showLet(result: Result): string { let { kind } = result // @ts-expect-error: a 'let' binding does not narrow 'result', so 'value' is still 'number | string' if (kind === "ok") return result.value.toFixed(1) return ""}Inferred type predicates
Section titled “Inferred type predicates”A function that returns a boolean expression can be a type predicate without saying so (TypeScript
5.5). The checker infers x is T when two things hold: narrowing the parameter to T when the
function returns true is valid, and the parameter is not T exactly when it returns
false. The second half is the one that fails:
type Ev = { kind: "job"; id: string } | { kind: "ping" }declare const events: (Ev | undefined)[]
const defined = events.filter((e) => e !== undefined) // Ev[]const truthy = events.filter((e) => !!e) // Ev[]: an object is never falsy
declare const ids: (number | undefined)[]const wrong = ids.filter((id) => !!id) // (number | undefined)[]: 0 is falsy
const jobs = events.filter((e) => e?.kind === "job") // (Ev | undefined)[]const asBool = events.filter((e) => Boolean(e)) // (Ev | undefined)[]
declare function takeEvents(events: Ev[]): voidtakeEvents(defined)// @ts-expect-error: the callback was not inferred as a predicatetakeEvents(asBool)!!id on a number fails the second half: false could also mean 0. e?.kind === "job" fails
because false does not mean e is not a job event, it could be a ping. When you do want the
narrower type, write the predicate yourself: (e): e is JobEvent => e?.kind === "job". It is
unchecked, as M1 warned, so keep it to one expression.
Callbacks and the reset
Section titled “Callbacks and the reset”Narrowing of a variable does not automatically carry into a function created after it. The checker cannot know when the callback runs, so it must assume the variable might have changed. The rule:
- A
const, a readonly property or a parameter that is never assigned keeps its narrowing inside closures. - A
letor an assigned parameter keeps it in an arrow function or function expression (not a hoisted function declaration) only if there is no assignment after the closure is created, and no assignment inside any nested function (TypeScript 5.4). Before 5.4 it reset in every closure.
function keep(id: string | undefined) { if (id === undefined) return const length = () => id.length // fine: id is never assigned return length}
function keepAssigned(id: string | undefined) { if (id === undefined) return id = id.trim() return () => id.length // fine in 5.4+: the last assignment is before the closure}
function reset(id: string | undefined) { if (id === undefined) return // @ts-expect-error: id is assigned after this closure is created, so it is not narrowed inside const length = () => id.length id = undefined return length}The reverse mistake is more common: writing to a let inside a callback. The checker does not
see the write when it narrows the outer code:
type Ev = { kind: "job"; id: string } | { kind: "ping" }
function lastJobId(events: Ev[]): string | undefined { let found: string | undefined = undefined events.forEach((event) => { if (event.kind === "job") found = event.id }) // @ts-expect-error: 'found' is still narrowed to 'undefined' here, so it is 'never' inside the if if (found) return found.length return found}found was assigned undefined, so after the call the checker still believes it is undefined.
A for...of loop is not a callback, so the assignment is visible and the type is string | undefined. Prefer the loop.
Narrowing unknown objects with in
Section titled “Narrowing unknown objects with in”Since TypeScript 4.9, "id" in value on a value of type object (or a type with no id)
narrows to value & Record<"id", unknown>. That makes it possible to parse untyped input
without as:
function readId(raw: unknown): string | undefined { if (typeof raw === "object" && raw !== null && "id" in raw && typeof raw.id === "string") { return raw.id } return undefined}
function readIdBad(raw: unknown): string | undefined { if (typeof raw === "object" && raw !== null) { // @ts-expect-error: property 'id' does not exist on type 'object' return raw.id } return undefined}Where the analysis is too optimistic
Section titled “Where the analysis is too optimistic”Narrowing of a property access (config.retry) is kept until the checker sees an assignment to
that reference. It is not reset by a function call, since tracking what every call could mutate
is not feasible:
type Config = { retry?: { max: number } }declare function clearRetry(config: Config): void
function maxRetries(config: Config): number { if (config.retry === undefined) return 0 clearRetry(config) return config.retry.max // accepted: but clearRetry may have unset it}This is a deliberate trade-off, not a bug: invalidating on every call would force a re-check
after nearly every line. Lesson 5 lists it with the other known holes. The
defense is to copy to a const before the call (const retry = config.retry) or to avoid
mutating shared objects.
Exercise
Section titled “Exercise”Every function in the starter has a type error that Relay’s earlier version silenced with as or
!. Fix each one by restructuring the control flow: no casts, no !, no any.
- Types at a reference come from walking the flow graph backwards: conditions, assignments,
returnandthrowall contribute. - A
never-returning call ends a path only when the callee has an explicit type: usefunctiondeclarations forfailandasserthelpers. - Aliased conditions need a
constalias, a never-reassigned reference, and at most five hops. Destructuredconstdiscriminants narrow their siblings and the original object. - Inferred predicates need the check to be reversible:
!== undefinedyes,!!non numbers no. - Closures keep narrowing for
constand forletwith no later assignment (5.4); writes inside a callback are invisible to the outer code. - Property narrowing survives function calls: copy to a
constbefore calling.
Further reading
Section titled “Further reading”- TypeScript 4.4: Control Flow Analysis of Aliased Conditions and Discriminants: the alias rules and limits.
- TypeScript 4.6: Control Flow Analysis for Destructured Discriminated Unions: narrowing across destructured variables.
- TypeScript 5.4: Preserved Narrowing in Closures Following Last Assignments: when closures keep narrowing.
- TypeScript 5.5: Inferred Type Predicates: when a function gets an inferred predicate.