Skip to content

no-mutable-global ​

Module-level mutable state: a let/var at module level, or a module-level value changed from inside a function.

Why: state any function can change at any time makes behaviour depend on call order, leaks data between requests and tests, and breaks when code runs twice. Guide, with the patterns that replace it: State without globals.

✕ Rejectedno-mutable-global
ts
let currentUser = "anonymous";

export function login(name: string): void {
  currentUser = name;
}

export function whoAmI(): string {
  return currentUser;
}

✅ Accepted: the caller owns the value

✓ Accepted0 diagnostics
ts
export type Session = { readonly user: string };

export function login(name: string): Session {
  return { user: name };
}

export function whoAmI(session: Session): string {
  return session.user;
}

Changing a module-level object, array, Map or Set from a function is the same problem:

✕ Rejectedno-mutable-global
ts
const stats = { hits: 0 };
const log: string[] = [];

export function hit(path: string): void {
  stats.hits++;
  log.push(path);
}

✅ Accepted: a factory gives each user of it its own instance

✓ Accepted0 diagnostics
ts
export function createStats() {
  const log: string[] = [];
  let hits = 0;
  return {
    hit(path: string): void {
      hits++;
      log.push(path);
    },
    summary: (): string => `${hits} hits, last: ${log.at(-1) ?? "none"}`,
  };
}

Allowed: module-level const values that are never changed, setting things up while the module loads (const m = new Map(); m.set(...) at top level), and a memo marked /** @cache */ (/** @cache */ const hashes = new WeakMap()), which may only hold what can be computed again: Caches. In test files, a module-level let that only the setup hooks and the tests assign (beforeEach, test(...), ...): Sharing setup.

Method calls count when the method changes its receiver: the changing methods of built-ins (Map.set, Date.setHours, exec on a g regex, ...), and methods of your own classes and object literals that change a field, directly or through other methods, across files. Lending module-level state from a function (mut(cache)), or passing it to a function's Mut<...> parameter, counts too. How it works: How the checker decides what changes state.

✕ Rejectedno-mutable-global
ts
class Counter {
  #count = 0;

  increment(): number {
    this.#count++;
    return this.#count;
  }
}

const requests = new Counter();

export function nextRequestId(): number {
  return requests.increment();
}

It follows aliases (const s = state.a.b; s.x = 3 changes state), and setting a property of the global object in a function, which makes a global variable without a let:

✕ Rejectedno-mutable-global
ts
import type { Option } from "@evobug_com/safe-ts-std/result";

declare global {
  var lastError: Option<string>;
}

const settings = { theme: { dark: false } };

export function toggle(): void {
  const theme = settings.theme;
  theme.dark = !theme.dark;
}

export function fail(message: string): void {
  globalThis.lastError = message;
}

Setting a global once at module level is allowed (a debug handle for the console, say). In a test file the message points to vi.stubGlobal(name, value), which sets a global for one test (vi.unstubAllGlobals() undoes it).

What reaches module state ​

Module state is followed from a function the way a borrowed parameter is (no-param-mutation): destructured (object and array patterns, nested, with defaults, a rest), a part through for...of, forEach, map, find, at or an index, a list or an object made in the function that holds it, a shallow copy ({ ...CONFIG } shares what its fields hold; its own slots are the function's), and what a function hands back: a function, an arrow in a const, a namespace's function or a method of a class (a static one too: a class's static fields are module state) that returns the state or a part of it, in this file or another, on some path (if (shared) return getHidden(); return fresh(); hands it back: the caller can't tell which it got), also through a second function, a helper of the calling function's own that takes no parameters (const again = () => getHidden()) included. Most code reaches a singleton that way (getConfig(), useStore(), registry()), and each of these changes it as much as CONFIG.retries = 2 does.

✕ Rejectedno-mutable-global
ts
type Config = { retries: number; hosts: string[]; inner: { depth: number } };
const CONFIG: Config = { retries: 1, hosts: [], inner: { depth: 0 } };

function current(): Config {
  return CONFIG;
}

export function tune(): void {
  const { inner, hosts } = CONFIG;
  inner.depth = 9;
  hosts.push("x");
  current().retries = 7;
}

✅ Accepted: the caller owns the value, or only reads it

✓ Accepted0 diagnostics
ts
type Config = { retries: number; hosts: string[]; inner: { depth: number } };
const CONFIG: Config = { retries: 1, hosts: [], inner: { depth: 0 } };

function fresh(): Config {
  return { retries: CONFIG.retries, hosts: [...CONFIG.hosts], inner: { ...CONFIG.inner } };
}

export function tuned(): Config {
  const config = fresh();
  config.inner.depth = 9;
  config.hosts.push("x");
  return config;
}

export function depth(): number {
  const { inner } = CONFIG;
  return inner.depth;
}

Whether a function hands back module state is worked out once per function and decided where it is called, across files, as for a parameter's part (no-param-mutation's "what a call hands back"). A function that returns a new object (structuredClone(CONFIG), a literal with every part copied) hands back none, and a read is never a change. The same part changed again through what one call hands back is one finding, at the first; a lend of a part (deepen(mut(getHidden() .inner))) is a change of that part. A package's function hands back none of the program's state.

Event emitters that collect subscribers ​

A module-level const holding an event emitter is shared state too, though nothing assigns to it: every listener added to it from a function, and every object made in a function that subscribes to it, stays alive as long as the module, with everything it holds. One shared icon that every new badge listens to keeps every badge ever made, and the screen each belongs to. The rule reports such an emitter subscribed to from a function (bus.on("saved", ...), addEventListener without { signal } or { once: true }, subscribe(...)), or handed to new X(...) there. The listener may be written in place, which can't be removed at all, or passed in (a parameter, this.onTick.bind(this)): each call adds the caller's. Not reported: a listener the file removes again from the same emitter (off, removeListener, removeEventListener, with the same parameter or this.onTick), a subscribe(...) whose result (the way to stop) is kept, and a module-level function, which is the same listener each time and holds nothing per call. Subscribing while the module loads isn't reported either: it happens once.

✕ Rejectedno-mutable-global
ts
import { EventEmitter } from "node:events";

const orders = new EventEmitter();

export function onOrder(notify: (id: string) => void): void {
  orders.on("placed", (id: string) => notify(id));
}

const ticks = new EventTarget();

export function subscribe(onTick: (event: Event) => void): void {
  ticks.addEventListener("tick", onTick);
}

✅ Accepted: the emitter belongs to the context that owns its listeners

✓ Accepted0 diagnostics
ts
export type Shop = { readonly orders: EventTarget; readonly lifetime: AbortController };

export function createShop(): Shop {
  return { orders: new EventTarget(), lifetime: new AbortController() };
}

export function onOrder(shop: Shop, notify: (id: string) => void): void {
  shop.orders.addEventListener("placed", () => notify("latest"), { signal: shop.lifetime.signal });
}

const ticks = new EventTarget();

// The caller gets the way out: the listener goes when it calls it.
export function subscribe(onTick: (event: Event) => void): () => void {
  ticks.addEventListener("tick", onTick);
  return () => ticks.removeEventListener("tick", onTick);
}

What counts as an emitter: EventTarget and EventEmitter (Node's node:events, and any package's class of that name), the platform's event targets (WebSocket, Worker, BroadcastChannel, ...), classes the packs describe as extending one, and your own classes extending one. A package's own emitter classes (a graphics library's shared geometry, say) are listed in package.json:

jsonc
"safe-ts": { "emitters": ["shop-ui Icon", "Observable"] }

An entry is module Class, or a class name for any module (your own classes too). A value built by calls on a new one (const ICON = new Icon("cart").tint("#333")) counts. Plain frozen data never does. Vue's reactive() objects aren't included: a watch made in a component's setup is stopped when the component unmounts, which removes its subscription, so a module-level reactive object doesn't keep them.

A module-level latest(...) ​

std's latest(...) holds the run in progress: each run(...) aborts the one before it. Made at module level, it is one run in progress for every caller: a second screen's search aborts the first screen's, and one owner's abort() stops everybody's. The rule reports const search = latest(...) at module level, like a let. Create it where its owner lives: in a component's setup, a page object, or the function that mounts the screen, with the owner's AbortSignal.

✕ Rejectedno-mutable-global
ts
import { latest } from "@evobug_com/safe-ts-std/async";
import type { Result } from "@evobug_com/safe-ts-std/result";

declare function searchUsers(query: string, signal: AbortSignal): Promise<Result<readonly string[], string>>;

export const search = latest((signal, query: string) => searchUsers(query, signal));

✅ Accepted: each mounted screen has its own

✓ Accepted0 diagnostics
ts
import { latest } from "@evobug_com/safe-ts-std/async";
import type { Result } from "@evobug_com/safe-ts-std/result";

declare function searchUsers(query: string, signal: AbortSignal): Promise<Result<readonly string[], string>>;

export function mountSearch(page: AbortSignal) {
  return latest((signal, query: string) => searchUsers(query, signal), page);
}

Packages: registries ​

A package's module-level objects are shared by everything that imports the package. Changing one from a function (a plugin registry's add) is reported with its own message: it changes them again each time the function runs, for every user of the package. Register once, at module load, where it happens once. Guide: State without globals.

A package's or the platform's prototype changed anywhere (Batcher.prototype.begin = ..., Object.defineProperty(proto, ...), a helper that patches the prototype it is given) is no-foreign-prototype-patch's, and only its: patching once at module load doesn't help there, because the module can run again while the package stays loaded. That rule's advice (wrap or subclass) holds, and its safe-ts-ignore covers the line. A prototype of the module's own class changed from a function is still reported here.

A setter next to the state ​

Moving the change into a function exported by the module that owns the state (export const setUser = (name: string) => { user.value = name; }) doesn't make it less shared: every importer changes the same value, in whatever order they run. It is reported like any other change, and so is lending that state (mut(state)) from inside the module. Make the state part of something created once and passed down (a factory, provide), or, in a Vue app, a Pinia setup store: the store's setup function runs once per Pinia instance, so its refs, lets and maps are not module-level state (Vue: Pinia stores).

One sanctioned global per module? ​

There is no marker that makes a module-level variable writable from functions. It would mark exactly what this rule is about, state any function can change in any order, without making it any less shared, and the checker couldn't verify anything about it (unlike @cache, whose promise is that every result stays the same with an empty cache). What the use cases need exists: a handle set once at module level (globalThis.app = createDebugHandle(context), whose functions read the current state from the context they were made with), vi.stubGlobal in tests, and a context object passed down for anything a page or a test boots again.

What the rule can't see: a value whose type isn't visible from how it is made (const db = createDb() without a type annotation, classes from packages): for those it only knows the method names of arrays, maps and sets, and a package's emitter classes only when listed in "emitters". A { signal } passed to a listener is taken as proof that it is removed, and so is a remove call for the same listener anywhere in the file; whether the signal is ever aborted, or the remove call ever runs, isn't checked. Getters that change the instance, a reference stored in another object, and writes deeper into the global object (globalThis.x.y = v; most are the platform's, like window.location.href = url) are not followed. Of what reaches module state: a let given another value later, a container made in the function and lent whole (mut({ base: EMPTY })), a copy of a namespace's function (const f = ns.current; f()), a getter of a class instance that isn't itself module state, a method of an object literal that returns other state than its own, a local helper that takes parameters, and a call given an object of the caller's own as well (pick(order): the call is asked whether it hands back order, not whether it hands back module state).

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra