Skip to content

The unsoundness catalog

A Relay worker pulled a Job[] from a queue, passed it to a helper that accepts “jobs or drafts”, and later called jobs[0].id on an array that now held a draft. No any, no cast, no error. This is not a bug in the checker. TypeScript’s design goals say it is not trying to be a sound type system. It trades some guarantees for code that is easy to write.

This lesson is a catalog. Each entry has a Relay bug that type-checks, what happens at runtime, and what closes it: a compiler flag, a design change, or a lint rule. Knowing the list matters more than memorizing the rules, because the holes are where the checker’s answer and the runtime disagree.

All examples compile under the strict config of this course (strict, noUncheckedIndexedAccess, exactOptionalPropertyTypes). Where a hole is closed by one of those flags, the example shows the error.

Job[] is assignable to (Job | Draft)[]. Reading from it is safe. Writing is not:

interface Job {
readonly id: string
}
interface Draft {
readonly draft: true
}
function addDraft(list: (Job | Draft)[]) {
list.push({ draft: true })
}
const jobs: Job[] = [{ id: "1" }]
addDraft(jobs) // compiles
// jobs is now [{ id: "1" }, { draft: true }]: jobs[1].id is undefined

Array<T> is covariant in T because its methods are compared bivariantly (entry 2). A real contravariant check on push would reject this call, and also reject a lot of ordinary code.

Closes it: take readonly (Job | Draft)[]. ReadonlyArray has no mutators, so covariance is sound there.

interface Job {
readonly id: string
}
interface Draft {
readonly draft: true
}
function withDraft(list: readonly (Job | Draft)[], draft: Draft): (Job | Draft)[] {
// @ts-expect-error: a readonly array has no push
list.push(draft)
return [...list, draft]
}

Make “does not mutate its input” part of the signature. The lint rule prefer-readonly-parameter-types can enforce it.

With strictFunctionTypes (part of strict), function-typed properties are checked contravariantly in their parameters. Methods are exempt. Method syntax and property syntax mean different things:

interface Job {
readonly id: string
}
interface Webhook {
readonly source: string
}
interface MethodStyle<E> {
handle(event: E): void
}
interface PropertyStyle<E> {
handle: (event: E) => void
}
declare const onJob: MethodStyle<Job>
const wide: MethodStyle<Job | Webhook> = onJob // compiles: a Job handler now receives a Webhook
declare const strictJob: PropertyStyle<Job>
// @ts-expect-error: the parameter is checked contravariantly
const strictWide: PropertyStyle<Job | Webhook> = strictJob

At runtime wide.handle({ source: "github" }) runs a function that reads event.id and gets undefined. The exemption exists so that Array<Dog> stays assignable to Array<Animal> and DOM types keep working (variance shows the rule).

Closes it: declare callbacks as properties with arrow types, not as methods, in your own interfaces. The lint rule method-signature-style can enforce the property form.

The checker narrows t.state after a check and keeps that narrowing across calls, because invalidating on every call would make narrowing useless:

interface Task {
state: "queued" | "running"
}
declare function start(task: Task): void
function run(task: Task) {
if (task.state === "queued") {
start(task) // sets task.state = "running"
const s: "queued" = task.state // compiles: the checker still believes "queued"
// @ts-expect-error: the checker thinks "running" is impossible here
if (task.state === "running") {
console.log(s)
}
}
}

The second error is the cruel part: the correct check is rejected as “no overlap”, so a careful developer deletes it. Lesson 3 shows when narrowing resets. A call never resets it.

Closes it: do not mutate shared objects through a call. Make the fields readonly and return a new value from start.

interface Task {
readonly state: "queued" | "running"
readonly attempts: number
}
function start(task: Task): Task {
return { state: "running", attempts: task.attempts + 1 }
}

Without noUncheckedIndexedAccess, byId["x"] has type Job, though the key may be missing. The flag adds undefined, and this course turns it on:

interface Job {
readonly id: string
}
declare const byId: Record<string, Job>
declare const queue: Job[]
// @ts-expect-error: 'job' is possibly 'undefined'
byId["missing"].id
// @ts-expect-error: indexing an array is also possibly undefined
queue[0].id

It is not complete. A fixed-length tuple has known indexes, and the checker trusts them even after the tuple was mutated:

interface Job {
readonly id: string
}
declare const a: Job
declare const b: Job
const pair: [Job, Job] = [a, b]
pair.pop()
console.log(pair[1].id) // compiles, TypeError at runtime: pair[1] is undefined

Checking queue.length > 0 does not narrow queue[0] either, so that case stays an error, which is the safe side.

Closes it: noUncheckedIndexedAccess for arrays and records, readonly [Job, Job] for tuples (no pop, no push).

timeoutMs?: number says “the key may be absent”. Without exactOptionalPropertyTypes, { timeoutMs: undefined } is also accepted, and the key is present with the value undefined. Spreading it over defaults then erases the default. Objects showed that bug. With the flag on, the two cases are separate types:

interface Settings {
timeoutMs?: number
}
// @ts-expect-error: undefined is not number, with exactOptionalPropertyTypes
const a: Settings = { timeoutMs: undefined }
interface Explicit {
timeoutMs?: number | undefined
}
const b: Explicit = { timeoutMs: undefined }
interface Full {
timeoutMs: number
}
declare const defaults: Full
declare const overrides: Explicit
// @ts-expect-error: the spread may leave undefined in a required field
const merged: Full = { ...defaults, ...overrides }

Write | undefined only where the value really can be undefined. The spread error is the payoff: the compiler now sees what the runtime does.

any switches the checker off for everything it touches, and the standard library hands it out:

interface Job {
readonly id: string
readonly kind: string
}
const job: Job = JSON.parse('{"id": 1}') // compiles: JSON.parse returns any
declare const response: { json(): Promise<any> }
async function load(): Promise<string> {
const body = await response.json()
return body.items[0].name // compiles whatever the body is
}
function decode<T = any>(raw: string): T {
return JSON.parse(raw)
}
const loose = decode("1") // any: the default filled the missing type argument
console.log(job, loose.anything.goes)

One leak is closed already. Under strict, useUnknownInCatchVariables makes catch (e) give e: unknown:

try {
JSON.parse("{")
} catch (e) {
// @ts-expect-error: 'e' is of type 'unknown'
console.log(e.message)
console.log(e instanceof Error ? e.message : String(e))
}

Closes it: declare the value unknown and narrow it with a guard that checks the fields. Lint rules no-explicit-any, no-unsafe-assignment, no-unsafe-member-access and no-unsafe-return find the rest. Do not default a type parameter to any: use unknown.

interface Job {
readonly id: string
readonly kind: string
}
function isJob(value: unknown): value is Job {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
typeof value.id === "string" &&
"kind" in value &&
typeof value.kind === "string"
)
}
function parseJob(raw: string): Job {
const value: unknown = JSON.parse(raw)
if (!isJob(value)) throw new Error("invalid job")
return value
}

A type predicate is itself a promise the checker does not verify. If isJob returned true always, it would compile. The guard is only as good as its body.

value as Job does not convert anything. It tells the checker to trust you, and the checker allows it when either type is comparable to the other (lesson 1). Two escape hatches stay open:

interface Job {
readonly id: string
}
declare const raw: unknown
const a = raw as Job // from unknown: always allowed
const b = { id: 1 } as unknown as Job // through unknown: always allowed
// @ts-expect-error: string and number do not overlap, so a direct assertion fails
const c = { id: 1 } as Job
console.log(a, b, c)

as unknown as T is the signature of a lie. Closes it: a guard or parser instead of an assertion; lint consistent-type-assertions and no-unnecessary-type-assertion; and a rule in code review that every as unknown as needs a comment saying what makes it true.

This looks like a hole and is the opposite. Object.keys(x) is typed string[], not (keyof T)[], because a value of type { a: number } may have more keys at runtime:

const wide = { a: 1, b: 2 }
const narrow: { a: number } = wide // fine: structural subtyping
const keys: string[] = Object.keys(narrow) // ["a", "b"] at runtime
// @ts-expect-error: 'b' is a key at runtime but not in keyof { a: number }
const typed: (keyof typeof narrow)[] = Object.keys(narrow)
console.log(keys, typed)

The compiler is sound here and the instinct to “fix” it with as (keyof T)[] is what creates a bug: Relay iterating Object.keys(headers) as (keyof Headers)[] would meet a header it never modeled. Iterate with Object.entries and a guard, or keep the keys in a typed tuple.

Since TypeScript 5.0 every enum is a union enum and a literal outside its members is rejected. A value typed number is still accepted:

enum Priority {
Low,
High,
}
// @ts-expect-error: 7 is not a member
const a: Priority = 7
declare const fromDb: number
const b: Priority = fromDb // compiles, whatever the number is
console.log(a, b)

A Priority column that holds 7 flows through every switch (priority) as if it were valid, and the default branch the type says is never runs. Closes it: a const object with a union type, plus one parse function at the boundary.

const Priority = { Low: 0, High: 1 } as const
type Priority = (typeof Priority)[keyof typeof Priority]
function toPriority(n: number): Priority {
if (n === Priority.Low || n === Priority.High) return n
throw new Error("invalid priority")
}
declare const fromDb: number
// @ts-expect-error: a plain number is not a Priority
const p: Priority = fromDb
console.log(toPriority(fromDb), p)

Enums also emit runtime code, which type-stripping setups reject (lesson 9). Another reason to prefer the object.

Three smaller holes share one cause: the checker compares shape, and the runtime has identity.

Spread loses the prototype. TypeScript knows that spreading a class instance drops methods, and says so. A class with only fields has nothing to drop, so the copy is assignable and is no longer an instance:

class Attempt {
constructor(public n: number) {}
}
class Job {
constructor(public id: string) {}
label() {
return this.id
}
}
const copy: Attempt = { ...new Attempt(1) } // compiles
console.log(copy instanceof Attempt) // false
// @ts-expect-error: the spread type has no label()
const job: Job = { ...new Job("1") }
console.log(job)

A #private field makes a class nominal. A literal or a spread cannot supply it:

class Attempt {
#brand = true
constructor(public n: number) {}
}
// @ts-expect-error: property '#brand' is missing
const forged: Attempt = { n: 1 }
console.log(forged)

readonly is not checked on assignment. { readonly a: number } is assignable to { a: number }, so a mutable alias reaches a frozen object. {} is not “an object”. It accepts 1 and "s"; it only rejects null and undefined. Both are worked through in lesson 1, with the fixes (a separate type, object).

Hole Closed by
1 array covariance readonly T[] parameters
2 method bivariance property-style callbacks (strictFunctionTypes)
3 narrowing survives calls immutable data, return new values
4 index access noUncheckedIndexedAccess, readonly tuples
5 optional vs undefined exactOptionalPropertyTypes
6 any leaks unknown plus guards, no-unsafe-* lint rules
7 assertions guards, consistent-type-assertions
8 Object.keys nothing to close: do not cast
9 numeric enums const object union, parse at the boundary
10 structure vs identity #private brand, object instead of {}

The starter has five of these holes, one per area: an array parameter, a method-style handler, a mutable task, JSON.parse returning any, and a numeric enum. Change the types and add the guards so the type tests’ @ts-expect-error lines hold and the runtime tests pass.

  • TypeScript is unsound on purpose. The holes are known, and each has a flag, a design, or a lint rule.
  • Arrays are covariant and methods are bivariant, so mutation through a wider type compiles. Take readonly arrays and declare callbacks as properties.
  • Narrowing is never reset by a call. Do not mutate shared objects through a function.
  • noUncheckedIndexedAccess covers arrays and records but not mutated tuples.
  • exactOptionalPropertyTypes separates “absent” from undefined, which fixes spread-over-defaults bugs.
  • JSON.parse, response.json() and T = any leak any. Declare unknown and guard.
  • as is a promise, and as unknown as is an unchecked one. Object.keys returning string[] is the sound choice.
  • A numeric enum accepts any number. Use a const object and parse at the boundary.