Skip to content

Immutability

Relay’s admin dashboard shows a snapshot of the state: the routes of every source and the job counts. The first version kept one state object and updated it in place with push and +=. The dashboard held on to “the previous snapshot” to show what changed, but the previous snapshot was the same object, so it always showed no change. Worse, a half-finished edit was visible to the render in the middle.

If values never change after they are created, a snapshot is just a reference, and you can hand the same value to ten readers without asking who might modify it. This lesson is about getting there in TypeScript without copying the world on every update.

readonly on a property or an array stops writes through that type. It was introduced in arrays. Readonly<T> applies it to every property of T, but only one level deep:

interface Route {
id: string
target: string
}
interface RelayState {
routes: Record<string, Route[]>
}
const state: Readonly<RelayState> = { routes: { github: [{ id: "g1", target: "slack" }] } }
// @ts-expect-error: Readonly makes the property read-only
state.routes = {}
// Not an error: Readonly is shallow, so the inside is still writable.
state.routes["github"] = []

To protect the whole tree either write readonly at every level, or use a recursive type. The recursive types lesson builds DeepReadonly:

type DeepReadonly<T> = T extends (infer U)[]
? ReadonlyArray<DeepReadonly<U>>
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T
interface Route {
id: string
target: string
}
type State = DeepReadonly<{ routes: Record<string, Route[]> }>
declare const state: State
// @ts-expect-error: the arrays are readonly all the way down
state.routes["github"]?.push({ id: "g2", target: "http" })
const first = state.routes["github"]?.[0]
if (first) {
// @ts-expect-error: and so are the objects inside them
first.target = "email"
}

For Relay’s own types it is clearer to write readonly where it belongs and skip the generic. readonly is erased at runtime: it is a promise checked by the compiler, nothing more.

as const freezes a literal’s type: properties become readonly, arrays become readonly tuples and strings keep their literal types.

const defaultRoutes = [
{ id: "g1", target: "slack" },
{ id: "s1", target: "http" },
] as const
type DefaultTarget = (typeof defaultRoutes)[number]["target"]
// "slack" | "http"
// @ts-expect-error: a readonly tuple has no push
defaultRoutes.push({ id: "x", target: "email" })

Use it for configuration tables that you also want as types. It does not make anything safer at runtime either.

To “change” a value you build a new one that shares everything untouched. Spread copies one level, so you copy each level on the path to the change and nothing else:

interface Route {
readonly id: string
readonly target: string
}
interface State {
readonly routes: Readonly<Record<string, readonly Route[]>>
readonly total: number
}
function addRoute(state: State, source: string, route: Route): State {
const current = state.routes[source] ?? []
return {
...state,
routes: { ...state.routes, [source]: [...current, route] },
}
}

Three objects are new: the state, the routes record and one source’s array. Every other source’s array, and every route object inside it, is the same one as before.

That sharing is what keeps immutable updates cheap, and you can check it:

interface Route {
readonly id: string
readonly target: string
}
interface State {
readonly routes: Readonly<Record<string, readonly Route[]>>
}
declare function addRoute(state: State, source: string, route: Route): State
declare const before: State
const after = addRoute(before, "github", { id: "g3", target: "http" })
console.log(after === before) // false: something changed
console.log(after.routes["stripe"] === before.routes["stripe"]) // true: untouched, same array
console.log(after.routes["github"] === before.routes["github"]) // false: this one was replaced

Reference equality is also the cheap way to ask “did this change?”. A renderer or a cache can compare two references instead of two trees. That only works if updates that change nothing return the same object, so make that a rule: when a remove or a replace finds nothing to do, return the input.

push, sort, reverse, splice and index assignment mutate. Newer methods return a copy instead:

const queue: readonly string[] = ["a", "b", "c"]
const sorted = queue.toSorted((x, y) => y.localeCompare(x)) // ["c", "b", "a"]
const replaced = queue.with(1, "B") // ["a", "B", "c"]
const dropped = queue.toSpliced(0, 1) // ["b", "c"]
const flipped = queue.toReversed() // ["c", "b", "a"]
console.log(queue, sorted, replaced, dropped, flipped) // queue is unchanged

On a readonly string[], calling sort() is a type error, which is the point of the type. Relay’s old dashboard called jobs.sort(...) on the shared list and reordered it for everyone.

Object.freeze makes writes fail at runtime, and in strict mode the failed write throws:

const route = Object.freeze({ id: "g1", target: "slack" })
try {
// @ts-expect-error: the frozen type is readonly, and at runtime the write throws in strict mode
route.target = "email"
} catch (e) {
console.log(e instanceof TypeError)
}

Know its limits. It is shallow: a frozen object can hold a mutable array. Freezing deeply needs a walk over the tree, which costs time on every update and gives you nothing in production that the readonly types did not already give you at compile time. Use freeze in tests, as the exercise does, to catch code that mutates its input. Do not freeze on a hot path.

Write four immutable updates on Relay’s nested state: addRoute, removeRoute, retarget and moveJob. The tests pass deeply frozen state, so any mutation throws, and they compare untouched branches with ===. The starter returns the state unchanged.

  • readonly and Readonly<T> are compile-time only, and Readonly<T> is one level deep.
  • as const gives literal, readonly types to configuration data.
  • Copy each level on the path to the change with spread, and share the rest.
  • Structural sharing makes === a cheap “did it change?”, so return the same object when nothing changed.
  • Use toSorted, with, toSpliced and toReversed instead of the mutating versions.
  • Object.freeze is shallow and costs time: use it in tests, not on hot paths.