State without globals
Module-level mutable state can be modified by any function in any order—leaking one request's data into another and causing tests to interfere. SAFE-TS allows module-level constants, never mutable globals.
In short
- Prefer pure updates: take state as a parameter and return the next value.
- Scope stateful instances: create counters, caches, and buffers inside a factory function and pass the instance to callers.
- Inject dependencies: pass clocks, loggers, and databases in as parameters.
- Explicit in-place mutation: parameters are read-only unless typed
Mut<T>and lent at the call site withmut(value). - Internal memos: mark read-only cache fields with
/** @cache */.
❌ Rejected: state at module level
✕ Rejectedno-mutable-global
ts
let requestCount = 0;
const seen = new Map<string, number>();
export function track(url: string): void {
seen.set(url, Date.now());
}
export function count(): number {
return requestCount;
}Both are reported: the let, and seen.set(...) changing a module-level Map. Here's what to write instead, simplest first.
1. Pass state in, return the new state
Most of the time you don't need stored state at all. The function gets the current value and returns the next one; the caller decides where it's kept.
✓ Accepted0 diagnostics
ts
export type Cart = { readonly items: readonly string[]; readonly total: number };
export const emptyCart: Cart = { items: [], total: 0 };
export function addItem(cart: Cart, item: string, price: number): Cart {
return { items: [...cart.items, item], total: cart.total + price };
}
const cart = addItem(addItem(emptyCart, "book", 12), "pen", 2);
console.log(cart.total);emptyCart is a constant, which is fine. And addItem is easy to test: the same input always gives the same output.
A spread copies one level. { ...cart } is a new object, but its items is still the caller's list: addItem writes a new list ([...cart.items, item]) where it changes one, and changing the copy's items in place would be changing the caller's (Copies).
2. Let a function create the state
When something really has to remember things, create it inside a function. Each call makes a fresh one, so two tests or two requests never share it by accident.
✓ Accepted0 diagnostics
ts
export function createCounter(start = 0) {
let count = start;
return {
increment: (): number => ++count,
current: (): number => count,
};
}
const requests = createCounter();
requests.increment();
console.log(requests.current());The same works for a cache. users.set(...) is fine here: users belongs to one cache, not to the module.
✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";
export type User = { readonly id: string; readonly name: string };
export function createUserCache() {
const users = new Map<string, User>();
return {
get: (id: string): Option<User> => users.get(id),
remember: (user: User): void => {
users.set(user.id, user);
},
};
}Reusing a buffer
A scratch buffer at the top of a module is shared state too: two callers writing into it at once corrupt each other's output. Give the buffer to an encoder the caller creates and keeps. It grows the buffer when a message doesn't fit, and returns an exact copy, so what it returned stays valid after the next call:
✓ Accepted0 diagnostics
ts
export function createEncoder(initialSize = 256) {
let scratch = new Uint8Array(initialSize);
return {
encode(values: readonly number[]): Uint8Array {
if (scratch.length < values.length) scratch = new Uint8Array(values.length * 2);
for (let i = 0; i < values.length; i++) scratch[i] = values[i] ?? 0;
return scratch.slice(0, values.length);
},
};
}
// Once per connection, worker or test, not once per module:
const encoder = createEncoder();
console.log(encoder.encode([1, 2, 3]).length);Each caller now passes its encoder along, which changes call sites. What it costs to allocate instead, and the subarray trap for small buffers, are in Performance myths.
3. Pass dependencies in
Code that needs the time, a logger, a database or settings gets them as a parameter instead of reaching for a global. Then a test can pass a fixed clock and a fake database.
✓ Accepted0 diagnostics
ts
export type Deps = {
readonly now: () => number;
readonly log: (message: string) => void;
};
export function greet(deps: Deps, name: string): string {
deps.log(`greeting ${name}`);
return `Hello ${name}, it is ${new Date(deps.now()).toISOString()}`;
}
// In the application:
greet({ now: Date.now, log: console.log }, "Ada");
// In a test:
greet({ now: () => 0, log: () => {} }, "Ada");4. Create it once at startup, then pass it down
For app-wide things like a store or a connection pool, create one in your entry point and hand it to the code that needs it. The app still has exactly one, but it's created in one known place, and tests can make their own.
✓ Accepted0 diagnostics
ts
export type Settings = { readonly theme: "light" | "dark"; readonly fontSize: number };
export function createSettingsStore(initial: Settings) {
let current = initial;
const listeners = new Set<(settings: Settings) => void>();
return {
get: (): Settings => current,
update: (change: Partial<Settings>): void => {
current = { ...current, ...change };
listeners.forEach((listener) => listener(current));
},
subscribe: (listener: (settings: Settings) => void): void => {
listeners.add(listener);
},
};
}
export type SettingsStore = ReturnType<typeof createSettingsStore>;
export function applyDarkMode(store: SettingsStore): void {
store.update({ theme: "dark" });
}
// main.ts: the one place the store is created.
const store = createSettingsStore({ theme: "light", fontSize: 14 });
applyDarkMode(store);In a Vue app with Pinia, a setup store is that context, created per app by createPinia(): Pinia stores hold module state shows how module state moves into one.
The context's lifetime
A context that can end (a screen, a page booted again by a test harness, a server's request) gets an AbortController with it, and everything that subscribes to something living longer passes its signal. The lifetime's abort handler also destroys every third-party object that registered global listeners of its own (a renderer that listens to the window's resize, a media query watcher): no { signal } reaches those, and they keep the whole context alive until their destroy() runs. Event emitters the context uses belong in it too, not in a module-level const: one shared emitter that every new object of a screen subscribes to keeps all of them (no-mutable-global).
✓ Accepted0 diagnostics
ts
export type Screen = { readonly lifetime: AbortController; readonly changes: EventTarget };
export function openScreen(onResize: () => void, cleanup: () => void): Screen {
const screen = { lifetime: new AbortController(), changes: new EventTarget() };
window.addEventListener("resize", () => onResize(), { signal: screen.lifetime.signal });
// A library's object with window listeners of its own: destroyed with the screen.
screen.lifetime.signal.addEventListener("abort", () => cleanup(), { once: true });
return screen;
}Pass down what a function uses, though. When one context object holds everything (an App with its state, settings, router and API client), a function that reads only app.state.cart can take the cart: its signature then says what it needs, and a test doesn't have to build a whole App. With the idiomatic rules on, wide-param finds those parameters.
Constants are fine
Values that never change aren't state. as const or readonly makes TypeScript stop accidental writes too:
✓ Accepted0 diagnostics
ts
export const config = {
apiUrl: "https://api.example.com",
retries: 3,
} as const;
export const weekdays: readonly string[] = ["Mon", "Tue", "Wed", "Thu", "Fri"];
export function retryDelay(attempt: number): number {
return Math.min(1000 * 2 ** attempt, 30_000) * (attempt < config.retries ? 1 : 0);
}Filling something in while the module loads is fine too: it happens once, before anyone can use it.
✓ Accepted0 diagnostics
ts
const aliases = new Map<string, string>();
aliases.set("colour", "color");
aliases.set("centre", "center");
export function normalize(word: string): string {
return aliases.get(word) ?? word;
}Scratch space in a hot path
A per-frame loop that reuses a scratch object or list (to make no garbage) keeps it in the context, scene.sortScratch, or takes it as a Mut<T> parameter its caller owns. A module-level scratch object is shared state like any other: if two calls overlap (a callback, a nested call, a second instance in a test), one overwrites what the other is still using.
A /** @scratch */ mark for a module-level object "that holds nothing between calls" was considered and left out: the checker can't make it sound. That the object is fully written before it is read in each function can be checked, but that no other user of it runs in between can't: any call between the first write and the last read (to a package, a callback, a function in another file) could reach another function using the same object, and an await lets anything run. A check that rejected every such call would accept almost no real hot path. On the context, the question doesn't come up: each owner has its own.
✓ Accepted0 diagnostics
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";
type Point = { x: number; y: number };
export type Scene = { readonly items: readonly Point[]; readonly order: Point[] };
export function sortByDepth(scene: Mut<Scene>): readonly Point[] {
const order = scene.order;
order.length = 0;
for (const p of scene.items) order.push(p);
return order.sort((a, b) => a.y - b.y);
}Packages: registries and prototypes
A package's module-level objects (a plugin registry, a class's prototype) are shared by every module that imports the package. Changing a registry from a function is reported, with a message of its own: each call registers again, for every user of the package. Register at module load, once, in the module that needs it:
✓ Accepted0 diagnostics
ts
type Plugin = { readonly name: string };
declare const plugins: { add(plugin: Plugin): void };
// At module load: once, whoever imports this module first.
plugins.add({ name: "gift-cards" });
export function giftCardsEnabled(): boolean {
return true;
}A prototype is different: patching it at module load isn't enough, because the module runs again (a test booting the app again, a hot reload) while the package stays loaded, and each run wraps the last patch. no-foreign-prototype-patch reports every patch of a class the module doesn't own, at module level too, and through a helper (of the file or imported) that patches the prototype it is given. Where the change belongs to one use only, a subclass changes nothing shared: class TracingRenderer extends Renderer { override draw() { ... } }.
Don't change what you were given
An object passed to a function is still the caller's object. Change it, and you change the caller's data behind their back. So a function only reads its parameters, unless the type says Mut<T>. (This is Rust's &T and &mut T, if you know them.)
✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Point = { readonly x: number; readonly y: number };
// Reads its parameter, returns a new value.
export function moved(point: Point, dx: number): Point {
return { ...point, x: point.x + dx };
}
// Changes its parameter, and says so.
export function addPoint(points: Mut<Point[]>, point: Point): void {
points.push(point);
}
// The call lends the list: `mut(points)`, like Rust's `&mut points`.
export function path(from: Point, steps: number): Point[] {
const points: Point[] = [];
for (let i = 0; i < steps; i++) addPoint(mut(points), moved(from, i));
return points;
}ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Point = { readonly x: number; readonly y: number };
// Reads its parameter, returns a new value.
export function moved(point: Point, dx: number): Point {
return { ...point, x: point.x + dx };
}
// Changes its parameter, and says so.
export function addPoint(points: Mut<Point[]>, point: Point): void {
points.push(point);
}
// The call lends the list: `mut(points)`, like Rust's `&mut points`.
export function path(from: Point, steps: number): Point[] {
const points: Point[] = [];
for (let i = 0; i < steps; i++) addPoint(points, moved(from, i));
return points;
}Now you can tell from a function's signature whether it can change your data, and from a call which of its arguments it changes.
Lend it with mut
Mut<T> is a type of its own: TypeScript accepts a value at a Mut<T> parameter only from mut(value) (or from another Mut<T>). The mark mut adds says, for each property, what the callee may do with it: a property it may write must have the same type in the value and in the parameter, one it can only read (readonly, or a method it calls) may be narrower in the value. readonly is shallow, so what a readonly property holds is lent with the value and checked by the same rule, one level down and as deep as it goes: a { readonly dogs: Dog[] } lent as Mut<{ readonly dogs: Animal[] }> is refused (the callee can't replace the list, but it can push a cat into it). A value with more properties than asked for fits, as it does anywhere in TypeScript; a union narrowed to one member keeps the mark of the whole loan, so it is passed on where that member is asked:
| Assignment | Mut<T> before (= T) | Mut<T> now |
|---|---|---|
a Dog[] lent as Mut<Animal[]> (the callee pushes a cat) | accepted | refused |
{ x: 0 | 1 } lent as Mut<{ x: number }> (the callee writes 5) | accepted | refused |
a Map<string, 1> lent as Mut<Map<string, number>> (its set takes any number) | accepted | refused |
a Mut<Builder> passed on as Mut<Unit>, a number[] lent as Mut<number[] | Int32Array> (a member where its union is asked; a write that retags it is union-tag-write's) | accepted | accepted |
a { readonly dogs: Dog[] } lent as Mut<{ readonly dogs: Animal[] }>, also in a class's readonly field | accepted | refused |
a { readonly state: { on: 0 | 1 } } lent as Mut<{ readonly state: { on: number } }> | accepted | refused |
a function taking Mut<T> where (value: T) => void is asked for | accepted | refused |
a value passed to a Mut parameter without mut(...) | accepted | refused |
a Mut<T> read as T, Readonly<T>, or a covariant readonly view | accepted | accepted |
a Mut<T> parameter passed on to another Mut<T> parameter | accepted | accepted |
a value with more properties (a Tree where Mut<Entity> is asked, a subclass for its base) | accepted | accepted |
a writable list where Mut<readonly T[]> is asked, a typed array made with new for Mut<Float64Array> | accepted | accepted |
a tree whose nodes hold readonly children: readonly Node[], a narrower readonly leaf (readonly id: "a") | accepted | accepted |
a Mut<Unit> narrowed to Builder (a tag test, is, match, variant) passed on as Mut<Builder> | accepted | accepted |
a function that only reads, where (value: Mut<T>) => void is asked for | accepted | accepted |
A member is lent where its union is asked (Mut<number[]> where Mut<number[] | Int32Array> is), since the function may only do what every member allows; what would make it another member, a write through the union to a property its members type differently, is union-tag-write's. Each member is compared as any loan is: a Dog[] isn't lent as Mut<Animal[] | Int32Array>.
mut(value) returns value (the transform erases it, so it costs nothing), and an optional value stays optional: mut(maybe) is a Mut<T> | undefined, for a parameter of type Option<Mut<T>>. A fresh literal is lent with the place's type written, mut<Cost>({ ... }) or mut<number[]>([]) (the one type argument mut takes: nothing else holds the literal), since TypeScript types [] as never[]. A list whose elements the function changes is readonly Mut<T>[] (or ReadonlyMap<K, Mut<V>>, ReadonlySet<Mut<T>>), lent with mutEach(items): the list itself, as a read-only view (the callee changes the elements, not the list), with the call erased like mut(x), so it costs nothing at run time. A key chosen at run time (obj[key] = value with a generic key) is written through the plain view: const target: T = obj; target[key] = value, as TypeScript reads Mut<T>[K] from the intersection Mut is.
A method lends its own object with the class written: wipe(mut<Cart>(this)). TypeScript's this in a class is a type of its own (this may be a subclass), and the mark doesn't reach through it, so mut(this) is refused where Mut<Cart> is asked. this is a Cart or a subclass of it, which is what the method sees when it writes this.total itself, so the class written is no cast: the checker accepts mut<C>(this) in an instance method of class C (with its type parameters, mut<Box<T>>(this) in class Box<T>) and reports a type argument anywhere else. The other spellings are worse: const self: Cart = this hides the loan behind a copy of the reference, and a this: Cart parameter changes the method's signature for nothing.
✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
function wipe(cart: Mut<Cart>): void {
cart.total = 0;
}
export class Cart {
total = 0;
clear(): void {
wipe(mut<Cart>(this));
}
}ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
function wipe(cart: Mut<Cart>): void {
cart.total = 0;
}
export class Cart {
total = 0;
clear(): void {
wipe(this);
}
}Still refused, and what to write:
- A generic
Mut<T>passed on where a non-genericMut<Entity>is asked:Tmay make a property narrower. Don't make functions generic to avoid a refusal: TypeScript lets a generic body write the bound's type intoT's property (e.x += dxsets a0 | 1to 5), which the plainMut<Entity>refuses at the call. - A property narrower in the value where the function may write it: a
Stockwhosecoins: numberis optional in theCosta function changes (it may set it toundefined). Give the function the type it changes (Mut<Stock>), or make the property the same.
Not refused, because TypeScript lets the same value reach the parameter through a plain assignment first: a value lent as Mut<Record<string, number>> whose type requires its keys (the callee may delete one), as Mut<object> (Object.assign writes anything), or as a type with an optional property the value's type doesn't have.
Not refused either, and known holes of the type:
- A function in a writable property replaced by one that needs more: a
{ onEvent: (a: Animal) => string }lent asMut<{ onEvent: (d: Dog) => string }>; the callee installs a handler that reads a dog'sbark, and the caller still calls it with any animal. A type can't tell a property holding a function from a method, and a method compared both ways would refuse every subclass that overrides one (aSpritelent where itsContainerbase is asked, a typed array made withnew), so both are compared one way. The checker reads the syntax, which tells them apart:covariant-aliasreports the lend (mut(x), or aMutvalue passed on) where a writable property of function type in the parameter's type takes a narrower parameter, or returns a wider result, than the same property in the value's own written type. Both types are read as written, across files, through aliases, interfaces, intersections andMut<...>; where either side can't be read (a type only TypeScript infers, a package's, a generic one, a parameter without a written type), nothing is reported. Areadonlyproperty, a method written as a method (whichno-method-signaturekeeps out of app code) and a class's method aren't this. Make such a propertyreadonlywhere the function shouldn't replace it, or lend it as what it is (Mut<Wide>). - A
readonlyproperty holding a union, written through a property its members share: a{ readonly unit: Builder }lent asMut<{ readonly unit: Builder | Soldier }>; the callee writess.unit.kind = "soldier", which TypeScript allows on a union. What a property holds is accepted when each of its members fits some member asked for, so that a typed array'sArrayBufferfits whereArrayBufferLikeis asked. The write itself is refused byunion-tag-write: put a new object of the member it becomes.
Six rules check what TypeScript can't:
missing-mut: a value passed to aMutparameter, or put into a place declaredMut<...>(an initializer, a default, areturn, a field), withoutmut(...), for the editor and lint paths that don't run TypeScript, and where the value is already aMut(which TypeScript accepts): every loan says so.aliased-mut: one call that lendsxand also getsxor a part of it (transfer(mut(a), mut(a)),addAll(mut(cart), cart.items)), Rust's E0499 and E0502; and two loans alive at once, or the owner writing the object while it is lent, an async call holding one until its promise settles (Promise.all([f(mut(x)), g(mut(x))]), a loop that keeps the promises in a list, a listener that lends state it doesn't own, a method that keeps the promise in a field and returns).covariant-alias: aSub[](orBox<Sub>,Map<K, Sub>) bound to a writableBase[]local, field,returnor property, through which aBaselands in theSub[]: a call is covered byMut, an alias the function keeps isn't.union-tag-write: a write through a union to a property its members type differently (unit.kind = "archer"on aMason | Archer), which TypeScript accepts and after which the object says it is a member it isn't.readonly-dropped: a value with areadonlyproperty given a place where it is writable (const rw: Loose = frozen), which TypeScript accepts both ways: the annotation that takesreadonlyoff is the way aroundMut's refusal at the call.no-param-mutationandno-mutable-globalstart at the loan:mut(p)of a borrowed parameter,mut(state)of module-level state in a function.
Borrow only what you change
When one context object travels everywhere (app: Mut<App> in every function), the signature stops saying anything. Two rules bring Rust's checks back:
unneeded-mut(idiomatic): aMut<...>parameter the function never changes. Take it asT; callers keep compiling, since aMut<T>is aT(theirmut(x)is then reported as unneeded, with a fix that removes it).stale-read: a local read out of a parameter (const cart = app.state.cart), then a call that puts a new object in that place, then the local used again. It still holds the old one: read it again after the call.
The same goes for loops: don't change a list while a loop is going over it. Build a new one (filter, map), or loop over a copy: for (const x of Array.from(items)). (Array.from rather than [...items], which oxlint's unicorn/no-useless-spread reports in a for...of.) Deleting the entry the loop is on from a Map or Set is well defined in JavaScript, so for (const [id, s] of sessions) if (s.expired) sessions.delete(id) needs no copy. Compacting an array in place (items[kept++] = x) belongs in an index loop, not a for...of over it.
Classes count too
Calling a method that changes an object is a change. The checker follows your own classes to find out which methods do:
✕ Rejectedno-mutable-global
ts
class RateLimiter {
#hits = new Map<string, number>();
allow(ip: string): boolean {
const hits = (this.#hits.get(ip) ?? 0) + 1;
this.#hits.set(ip, hits);
return hits <= 100;
}
}
const limiter = new RateLimiter();
export function handle(ip: string): string {
return limiter.allow(ip) ? "ok" : "slow down";
}The message spells out the chain: limiter.allow() changes module-level limiter, because RateLimiter.allow calls this.#hits.set(), which changes a Map.
The same goes for a parameter, Rust's &mut self: limiter.allow(ip) on a limiter: RateLimiter the function only borrowed changes the caller's limiter, and no-param-mutation reports it; so does changing what a method hands out of its object (order.linesOf().push(x)), and a method or constructor that keeps a borrowed parameter in its object when the class changes it later. A getter must not change its object at all (mutating-getter): make it a method. Nothing needs to be written on the class: the checker reads the methods' bodies. A method declared in an interface has no body, so calls through one aren't followed.
✅ Accepted: whoever creates the limiter owns it
✓ Accepted0 diagnostics
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";
export class RateLimiter {
#hits = new Map<string, number>();
allow(ip: string): boolean {
const hits = (this.#hits.get(ip) ?? 0) + 1;
this.#hits.set(ip, hits);
return hits <= 100;
}
}
export function handle(limiter: Mut<RateLimiter>, ip: string): string {
return limiter.allow(ip) ? "ok" : "slow down";
}Caches: /** @cache */
Some functions only read their input, but remember what they worked out: a memo of search results, a buffer they reuse. Taking Mut<Catalog> for that says the function changes the catalog, which isn't true. Mark the field that holds the cache instead, in the type declaration:
✓ Accepted0 diagnostics
ts
type Hits = readonly string[];
export type Catalog = {
readonly products: readonly string[];
readonly hidden: ReadonlySet<string>;
/** @cache */
readonly searches: Map<string, Hits>;
};
export function search(catalog: Catalog, query: string): Hits {
const known = catalog.searches.get(query);
if (known !== undefined) return known;
const hits = catalog.products.filter((name) => name.includes(query) && !catalog.hidden.has(name));
catalog.searches.set(query, hits);
return hits;
}Changing a @cache field, or anything it holds, through a borrowed parameter is not reported by no-param-mutation. The field is found through the parameter's declared type: a type alias or interface in the same file or imported (not a generic one). A field with the same name in another type is still reported.
A class marks its memo the same way, on the field: a method or getter that only fills a /** @cache */ field doesn't change the object, for no-param-mutation, mutating-getter and no-mutable-global:
✓ Accepted0 diagnostics
ts
export class Prices {
readonly base: ReadonlyMap<string, number>;
/** @cache */
private readonly taxed = new Map<string, number>();
constructor(base: ReadonlyMap<string, number>) {
this.base = base;
}
withTax(item: string): number {
const known = this.taxed.get(item);
if (known !== undefined) return known;
const price = (this.base.get(item) ?? 0) * 1.2;
this.taxed.set(item, price);
return price;
}
}
export function total(prices: Prices, items: readonly string[]): number {
return items.reduce((sum, item) => sum + prices.withTax(item), 0);
}A module-level memo of a pure function works the same way, for no-mutable-global:
✓ Accepted0 diagnostics
ts
/** @cache */
const hashes = new WeakMap<object, string>();
export function rulesHash(rules: object): string {
const known = hashes.get(rules);
if (known !== undefined) return known;
const hash = Object.keys(rules).sort().join(",");
hashes.set(rules, hash);
return hash;
}The tag goes on a const. Its methods (hashes.set(...)) may be called from any file, and its properties set in its own file.
@cache is a promise the checker can't verify: the result of every function must be the same with an empty cache. Use it only for data that can be thrown away and computed again, never for state. safe-ts check counts the tags in its "escape hatches" line, next to unsafe().
How the checker decides what changes state
Assigning to a module-level value (config.debug = true, stats.count++) is always a change. A method call depends on what it's called on: cache.set(...) changes a Map, cache.get(...) doesn't. The checker works out what each module-level value is from how it's made (new Map(), [], /x/g, new Service(), an object literal) or from its type annotation, then:
- Built-ins have a list of the methods that change them:
push/splice/sort/... on arrays,set/delete/clearon maps,addon sets, theset*methods ofDate,append/set/deleteonURLSearchParams,HeadersandFormData, typed arrays, andexec/teston a regex with thegoryflag (they move itslastIndex). Built-in functions that change an argument count too:Object.assign(target, ...),Object.defineProperty,Reflect.set,Atomics.store, ... - Your own classes: a method changes the object if it assigns to a field (also through a local naming a part of the object, or an element of a field in a loop or a callback), calls a changing method on one, lends the object or a part of it (
mut<Cart>(this),mut(this.items)), or calls another method (this.save(),super.reset()) that does, across files and up theextendschain. Static methods and methods of object literals are followed the same way. Writing a/** @cache */field is no change. - Loans:
mut(state)in a function lends module-level state to be changed, and so does passing it to a parameter declaredMut<...>. - Aliases:
const s = state.a.b; s.x = 3in a function changesstate, the same asstate.a.b.x = 3. - What reaches it: module state is followed from a function the way a parameter that isn't
Mutis (no-param-mutation): destructured (const { inner } = CONFIG, nested, with defaults, an array pattern, a rest of its fields), iterated (for...of,forEach,map,find,at, an index), put into a list or an object made there ([CONFIG],{ config: CONFIG }), copied shallowly ({ ...CONFIG }: its own slots are the function's, what they hold is shared), and handed back by a function (current().retries = 7), an arrow in aconst, a namespace's function or a method of a class (a static one, with the class's static fields), in the same file or another, also through a second function that returns the first one's result and a helper of the calling function's own without parameters. Whether a function hands back module state is worked out once per function, as whether it hands back a part of a parameter is; one that returns a new object (structuredClone, a literal with every part copied) doesn't. - The global object: setting a property of
globalThis,window,selforglobalin a function makes or changes a global variable, so it counts too. At module level it is allowed: a handle set once while the module loads (globalThis.debug = { dump }) is like a module-level constant. In tests,vi.stubGlobalsets one for a test. - Event emitters: subscribing from a function to a module-level emitter, or handing it to
new X(...)there, adds to its listener list, which keeps what subscribed alive.
What the checker can't see
- Values whose type isn't visible where they're made:
const db = createDb()without a type annotation, or a class from a package. Then the checker falls back to the method names of arrays, maps and sets (push,set,delete,add, ...), so it can miss changes, and can flag adelete()that changes nothing. A type annotation (const db: Database = createDb()) tells it what the value is. - Getters that change module-level state through the object they are read on: reading
config.nextisn't a call. A getter that changes its object is reported at the getter (mutating-getter). - Copies of the reference stored elsewhere:
const s = serviceandconst s = state.a.binside a function are followed (s.save()changesservice), and so is an object or a list made there ([service],{ service }), but a reference kept in another object outside it (deps.service = service, thendeps.service.save()elsewhere) is not. Aletgiven another value later isn't followed from module state (it may hold the function's own by then), nor is a container made there lent whole (mut({ base: EMPTY, pages: [] })), nor a copy of a namespace's function (const f = ns.current; f().x = 1). - Methods declared in an interface or an object type: they have no body to read.
- Writes deeper into the global object:
globalThis.x = vin a function is reported, butglobalThis.x.y = vandglobalThis.x.push(v)aren't, because most such writes go to the platform's own objects (window.location.href = url).
Rules in this guide: no-mutable-global, no-param-mutation, mutating-getter, covariant-alias, union-tag-write, readonly-dropped, aliased-mut, no-mutation-while-iterating, stale-read, unneeded-mut