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, Readonly and deep readonly
Section titled “readonly, Readonly and deep readonly”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-onlystate.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 downstate.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
Section titled “as const”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 pushdefaultRoutes.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.
Immutable updates with spread
Section titled “Immutable updates with spread”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.
Structural sharing, proven with ===
Section titled “Structural sharing, proven with ===”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): Statedeclare const before: State
const after = addRoute(before, "github", { id: "g3", target: "http" })
console.log(after === before) // false: something changedconsole.log(after.routes["stripe"] === before.routes["stripe"]) // true: untouched, same arrayconsole.log(after.routes["github"] === before.routes["github"]) // false: this one was replacedReference 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.
Array methods that do not mutate
Section titled “Array methods that do not mutate”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 unchangedOn 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: cost and limits
Section titled “Object.freeze: cost and limits”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.
Exercise
Section titled “Exercise”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.
readonlyandReadonly<T>are compile-time only, andReadonly<T>is one level deep.as constgives 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,toSplicedandtoReversedinstead of the mutating versions. Object.freezeis shallow and costs time: use it in tests, not on hot paths.
Further reading
Section titled “Further reading”- Array.prototype.toSorted(): the non-mutating sort.
- Object.freeze(): what freezing does, and that it is shallow.