no-param-mutation
A function changes data it received as a parameter, or lends it to be changed (mut(x)), without declaring it Mut<...>.
Why: the parameter belongs to the caller. Changing it changes the caller's data behind its back: props.items.sort() reorders the parent's list, a "helper" that sets user.verified = true quietly edits the object in a cache. Like Rust's &T and &mut T: parameters are borrowed for reading, and a function that changes one says so in its signature. Guide: State without globals.
✕ Rejectedno-param-mutation
ts
type Order = { readonly id: string; lines: string[]; total: number };
export function addLine(order: Order, line: string, price: number): Order {
order.lines.push(line);
order.total += price;
return order;
}✅ Accepted: return a changed copy
✓ Accepted0 diagnostics
ts
type Order = { readonly id: string; readonly lines: readonly string[]; readonly total: number };
export function addLine(order: Order, line: string, price: number): Order {
return { ...order, lines: [...order.lines, line], total: order.total + price };
}✅ Accepted: declare it, when changing it is the point, and lend it at the call
✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
export function fillRandom(buffer: Mut<number[]>, count: number): void {
for (let i = 0; i < count; i++) buffer.push(Math.random());
}
export function sample(count: number): number[] {
const buffer: number[] = [];
fillRandom(mut(buffer), count);
return buffer;
}ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
export function fillRandom(buffer: Mut<number[]>, count: number): void {
for (let i = 0; i < count; i++) buffer.push(Math.random());
}
export function sample(count: number): number[] {
const buffer: number[] = [];
fillRandom(buffer, count);
return buffer;
}Mut<T> is the parameter's &mut T, and mut(buffer) is the caller's &mut buffer: the signature says the function changes its argument, and the call says which argument it lends. It changes nothing at run time (the transform erases mut(x) to x). TypeScript checks the type in both directions: a Dog[] can't be lent as Mut<Animal[]>, a value can't be passed without mut(...) (missing-mut), and a function taking Mut<T> doesn't fit a callback slot that only lends to read. The other way round, a Mut<...> parameter the function never changes, or mut(x) where the parameter isn't Mut, is unneeded-mut (idiomatic).
An optional parameter counts too: Mut<T> | undefined and Option<Mut<T>> are a Mut<T> once the missing case is handled. What a Mut parameter holds is the function's to change, in a callback as in a loop:
✓ Accepted0 diagnostics
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";
import type { Option } from "@evobug_com/safe-ts-std/result";
type Task = { column: number };
type Board = { tasks: Task[] };
export function moveAll(board: Mut<Board>, column: number): void {
board.tasks.forEach((task) => {
task.column = column;
});
}
export function reset(board: Option<Mut<Board>>): void {
if (board === undefined) return;
for (const task of board.tasks) task.column = 0;
}The same goes for what the function owns through a local alias, a for...of over it, and the callbacks inside the loop. A local array filled only with what the function owns (or makes) holds owned elements too:
✓ Accepted0 diagnostics
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";
type Line = { done: boolean };
type Order = { lines: Line[] };
type Shop = { orders: Map<string, Order> };
export function shipAll(shop: Mut<Shop>): void {
const orders = shop.orders;
for (const order of orders.values()) {
order.lines.forEach((line) => {
line.done = true;
});
}
}
export function clearLate(shop: Mut<Shop>, now: number): void {
const late: { order: Order; at: number }[] = [];
for (const order of shop.orders.values()) late.push({ order, at: now });
late.forEach(({ order }) => {
order.lines.length = 0;
});
}ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";
type Line = { done: boolean };
type Order = { lines: Line[] };
type Shop = { orders: Map<string, Order> };
export function shipAll(shop: Mut<Shop>): void {
const orders = shop.orders;
for (const order of orders.values()) {
order.lines.forEach((line) => {
line.done = true;
});
}
}
export function clearLate(shop: Mut<Shop>, now: number): void {
const late: { order: Order; at: number }[] = [];
for (const order of shop.orders.values()) late.push({ order, at: now });
{ const __la1 = late; for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let { order } = __le1; let __lv1_0; __lb1_0: {
order.lines.length = 0;
} }} }
}Such an array stops counting as owned when something that may be the caller's goes into it, or when it is handed to another function (which could put anything into it).
Mut on one field
An options object often carries one thing the function is meant to change and several it only reads. Declare that field Mut<...> in the parameter's type: what it holds is the function's to change, also through destructuring, while the other fields stay borrowed. Assigning the field itself (options.draft = ...) still changes the caller's object:
✓ Accepted0 diagnostics
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";
type Counter = { value: number };
type Options = { readonly step: number; readonly total: Mut<Counter> };
export function advance(options: Options): void {
options.total.value += options.step;
}
export function advanceTwice({ step, total }: Options): void {
total.value += step * 2;
}The type is followed like @cache fields: an alias or interface here or imported, a type written inline, Option<...>, unions and intersections.
Callbacks and platform objects
The changing methods of arrays, maps and sets (push, set, delete, clear, ...) count by name only where the receiver's type isn't known. Where the parameter's declared type makes the member a function (set: (value: string) => void, a method signature clear(): void), calling it calls a callback, not a collection's method, and isn't a change. A Map, Headers, URLSearchParams or a type without a declaration still counts.
The platform's request and event objects hand back their results through event-handler slots: request.onsuccess = ... on an IDBRequest, transaction.oncomplete on an IDBTransaction, reader.onload on a FileReader, socket.onmessage on a WebSocket. Setting an on... property of a parameter declared with a platform type subscribes to it, and so does event.dataTransfer.dropEffect (and effectAllowed) in a drag handler, which is how a handler answers the browser. Other fields of such an object are still the caller's (socket.binaryType = "arraybuffer" is reported), and so is an on... field of your own type:
✓ Accepted0 diagnostics
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
export class TransactionFailed extends PropagateError {}
export function finished(transaction: IDBTransaction): Promise<void> {
return new Promise((resolve, reject) => {
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(new TransactionFailed(String(transaction.error)));
});
}
export function allowMove(event: DragEvent): void {
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
}
type Field = { readonly label: string; readonly set: (value: string) => void };
export function pick(field: Field): void {
field.set(field.label);
}Setting a handler slot replaces the one that was there: for an element other code also listens to, addEventListener with a signal is still the better choice.
It also follows aliases, callbacks and non-null assertions (board.sync!.status = ...), because they all still reach the caller's data:
✕ Rejectedno-param-mutation
ts
type Todo = { title: string; done: boolean };
export function completeAll(todos: readonly Todo[]): void {
todos.forEach((todo) => {
todo.done = true;
});
}
export function clearTitles(list: { todos: Todo[] }): void {
const todos = list.todos;
todos.length = 0;
}ts
type Todo = { title: string; done: boolean };
export function completeAll(todos: readonly Todo[]): void {
{ const __la1 = todos; for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let todo = __le1; let __lv1_0; __lb1_0: {
todo.done = true;
} }} }
}
export function clearTitles(list: { todos: Todo[] }): void {
const todos = list.todos;
todos.length = 0;
}Vue props
The props of a Vue component (defineProps()) are the parent's data, borrowed the same way. Changing them is reported with a message about props, in the script and in the template, including v-model bound to a prop. Vue makes the props object read-only, but not the objects inside it: props.user.name = "x" works, and changes the parent's object without the parent knowing. Guide: Vue.
✕ Rejectedno-param-mutation
vue
<script setup lang="ts">
type Filters = { query: string; tags: string[] };
const props = defineProps<{ filters: Filters }>();
function addTag(tag: string): void {
props.filters.tags.push(tag);
}
</script>
<template>
<input v-model="props.filters.query" />
<button @click="addTag('new')">Add tag</button>
</template>✅ Accepted: let the parent change it
✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import { computed } from "vue";
type Filters = { readonly query: string; readonly tags: readonly string[] };
const filters = defineModel<Filters>({ required: true });
const query = computed({
get: () => filters.value.query,
set: (next: string) => {
filters.value = { ...filters.value, query: next };
},
});
function addTag(tag: string): void {
filters.value = { ...filters.value, tags: [...filters.value.tags, tag] };
}
</script>
<template>
<input v-model="query" />
<button @click="addTag('new')">Add tag</button>
</template>Setting a model's .value sends the new value to the parent (update:modelValue), and the parent's v-model stores it. Emitting your own event (emit("update", next)) works the same way. Destructured props (const { filters } = defineProps<...>()) are borrowed too.
A parent that hands a child a ref on purpose, for the child to write (a draft held by a store-like object, say), says so in the props' type: a field declared Mut<Ref<T>> is the child's to change, as for a function's Mut field. Everything else in the props stays the parent's. See Vue: a ref the parent hands over.
React props
A React component's props are a parameter like any other, so changing an object reached through them (destructured or not) is reported, in the component and in its handlers. React doesn't notice the change, and the parent's data no longer matches what it rendered. Guide: React.
✕ Rejectedno-param-mutation
tsx
type Filters = { query: string };
export function Search({ filters }: { filters: Filters }) {
return <input value={filters.query} onChange={(e) => { filters.query = e.target.value; }} />;
}✅ Accepted: the parent passes the function that changes it
✓ Accepted0 diagnostics
tsx
export function Search({ query, onQuery }: { query: string; onQuery: (query: string) => void }) {
return <input value={query} onChange={(e) => onQuery(e.target.value)} />;
}Callbacks get Mut from where they are passed
A callback written without a type for its parameter gets the type from where it is passed: the parameter of a project function (here or imported), or a variable's type annotation. When that type says Mut<...>, the callback owns the value, as if it were written (session: Mut<Session>) => ...:
✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Cart = { items: string[] };
type Session = { cart: Cart; visits: number };
export function withSession(change: (session: Mut<Session>) => void): void {
const session: Session = { cart: { items: [] }, visits: 0 };
change(mut(session));
}
withSession((session) => {
session.cart.items.push("tea");
});
type SessionEdit = (session: Mut<Session>) => void;
export const countVisit: SessionEdit = (session) => {
session.visits += 1;
};ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Cart = { items: string[] };
type Session = { cart: Cart; visits: number };
export function withSession(change: (session: Mut<Session>) => void): void {
const session: Session = { cart: { items: [] }, visits: 0 };
change(session);
}
withSession((session) => {
session.cart.items.push("tea");
});
type SessionEdit = (session: Mut<Session>) => void;
export const countVisit: SessionEdit = (session) => {
session.visits += 1;
};Lending it on: mut(x)
A loan starts where mut(x) is written, so that is where the check is: lending a borrowed parameter, or something reached through it (mut(order.lines)), to a function that takes it Mut<...> changes it all the same, and is reported, also from a closure (an event handler, a timer). A loan of module-level state from inside a function is no-mutable-global's:
✕ Rejectedno-param-mutation
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Cart = { coupon: string; total: number };
export function applyCoupon(cart: Mut<Cart>, code: string): void {
cart.coupon = code;
}
export function checkout(cart: Cart, code: string): void {
applyCoupon(mut(cart), code);
}
export function couponButton(cart: Cart, code: string): () => void {
return () => applyCoupon(mut(cart), code);
}ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Cart = { coupon: string; total: number };
export function applyCoupon(cart: Mut<Cart>, code: string): void {
cart.coupon = code;
}
export function checkout(cart: Cart, code: string): void {
applyCoupon(cart, code);
}
export function couponButton(cart: Cart, code: string): () => void {
return () => applyCoupon(cart, code);
}✅ Accepted: the signature says so
✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Cart = { coupon: string; total: number };
export function applyCoupon(cart: Mut<Cart>, code: string): void {
cart.coupon = code;
}
export function checkout(cart: Mut<Cart>, code: string): void {
applyCoupon(mut(cart), code);
}ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Cart = { coupon: string; total: number };
export function applyCoupon(cart: Mut<Cart>, code: string): void {
cart.coupon = code;
}
export function checkout(cart: Mut<Cart>, code: string): void {
applyCoupon(cart, code);
}The loan needs no lookup: mut(cart) of a borrowed cart is reported wherever it is written, also in a call the checker can't follow. Older code that passes the parameter without mut(...) is reported too where the callee declares the parameter Mut<...> (looked up across files, as declared: function f(cart: Mut<Cart>) or const f = (cart: Mut<Cart>) => ... at module level), together with missing-mut.
What a list holds
The objects a borrowed list or map holds are the caller's too, however the function reaches them: a for...of variable (also over .values(), .entries() with [key, value]), what find, findLast, at and get give back, an index (lines[0]), destructuring (const [first, ...rest] = lines), a callback's item (forEach, map, ...). A list and what it holds are different things: filter, slice, toSorted, concat, Array.from, Object.values and a spread ([...lines]) give a new list that holds the same objects, so pushing to it is the function's own business and changing an object in it is not. map and structuredClone give new objects. What each built-in hands back is data in crates/safe_ts_core/ecmascript/ecmascript-api.json (returns):
| What it hands back | Built-ins |
|---|---|
| one object the receiver holds | find, findLast, at, pop, shift (arrays), get (maps) |
| a new container with the same objects | filter, slice, splice, toSorted, toReversed, toSpliced, concat, flat, with, values(), entries() (arrays, maps, sets), Array.from (without a mapper), Object.values, Object.entries, [...xs] |
| the receiver itself | sort, reverse, fill, copyWithin (arrays), set (maps), add (sets) |
| new objects | map, flatMap, Array.from with a mapper (what the callback returns), structuredClone |
get is also the name of many a project method: a call the whole program follows into one of your classes is decided by that method's body instead. A list declared with Mut elements (readonly Mut<Unit>[], ReadonlyMap<string, Mut<Band>>) holds objects the function owns, and a new list of primitives (ids.slice() lent to Mut<number[]>) holds nothing of the caller's.
✕ Rejectedno-param-mutation
ts
type Line = { qty: number };
type Order = { readonly lines: Line[]; readonly byId: ReadonlyMap<string, Line> };
export function clear(order: Order): void {
for (const line of order.lines) line.qty = 0;
const big = order.lines.find((line) => line.qty > 9);
if (big !== undefined) big.qty = 9;
for (const line of [...order.byId.values()].filter((l) => l.qty > 1)) line.qty = 1;
}✅ Accepted: the function says it changes the lines (each is lent), or works on its own copies
✓ Accepted0 diagnostics
ts
import { type Mut, mutEach } from "@evobug_com/safe-ts-std/mut";
type Line = { qty: number };
export function clear(lines: readonly Mut<Line>[]): void {
for (const line of lines) line.qty = 0;
}
export function cleared(lines: readonly Line[]): Line[] {
const copies = lines.map((line) => ({ ...line }));
for (const line of copies) line.qty = 0;
return copies;
}
export function big(lines: readonly Line[]): number {
const kept = lines.filter((line) => line.qty > 9);
kept.push({ qty: 10 });
return kept.length;
}
export function run(): number {
const lines: Line[] = [{ qty: 1 }];
clear(mutEach(lines));
return lines.length;
}ts
import { type Mut, mutEach } from "@evobug_com/safe-ts-std/mut";
type Line = { qty: number };
export function clear(lines: readonly Mut<Line>[]): void {
for (const line of lines) line.qty = 0;
}
export function cleared(lines: readonly Line[]): Line[] {
const __la1 = lines; const __lr1: any[] = new Array(__la1.length); for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let line = __le1; __lr1[__li1] = (({ ...line })); }} const copies = __lr1;
for (const line of copies) line.qty = 0;
return copies;
}
export function big(lines: readonly Line[]): number {
const kept = lines.filter((line) => line.qty > 9);
kept.push({ qty: 10 });
return kept.length;
}
export function run(): number {
const lines: Line[] = [{ qty: 1 }];
clear(lines);
return lines.length;
}The quick fix for a change to an element is Declare that this function changes the elements of x: readonly Mut<…>[] where the parameter is written T[] or readonly T[]: the function changes the objects, not the list, and its callers lend each with mutEach(items): the list itself at run time, as a read-only view, with the call erased by the transform like mut(x) (items.map((item) => mut(item)) says the same and makes a new array; it is still accepted).
Copies
A shallow copy is a new object, or a new list, and its own slots are the function's: give a field of { ...order } a new value, push to [...order.lines, extra], sort it. What the slots hold is still whoever's it was: the copy's meta is order.meta, its elements are the caller's lines. So a change of anything reached through a field the copy took, or through an element a new list took, changes the caller's data, and is reported like the change written on the parameter; so is lending such a part with mut(...), and lending the copy whole where a field it took can hold an object. Every way of writing a copy counts: an object spread, with or without other properties, after other spreads or before them; Object.assign({}, order) and Object.assign({}, order, patch); a destructured rest (const { id, ...rest } = order); a list literal with a spread among other elements; Array.from(xs), xs.slice(), [...xs].sort(), new Map(byId), new Set(tags); a copy of a copy; and a copy a function of the program hands back (function clone(o: Order) { return { ...o }; }, then changed by its caller through a field).
✕ Rejectedno-param-mutation
ts
type Line = { done: boolean };
type Order = { readonly id: string; lines: Line[]; meta: { tag: string } };
export function renamed(order: Order): Order {
const copy = { ...order, id: "new" };
copy.meta.tag = "renamed";
return copy;
}
export function closed(order: Order, extra: Line): Line[] {
const list = [...order.lines, extra];
for (const line of list) line.done = true;
return list;
}✅ Accepted: copy the part too, give the field a value of its own, or copy all of it
✓ Accepted0 diagnostics
ts
type Line = { done: boolean };
type Order = { readonly id: string; lines: Line[]; meta: { tag: string } };
export function renamed(order: Order): Order {
const copy = { ...order, id: "new", meta: { ...order.meta } };
copy.meta.tag = "renamed";
return copy;
}
export function closed(order: Order, extra: Line): Line[] {
const list = [...order.lines.map((line) => ({ ...line })), extra];
for (const line of list) line.done = true;
return list;
}
export function retitled(order: Order): Order {
const copy = { ...order };
copy.meta = { tag: "retitled" };
copy.meta.tag = "retitled twice";
return copy;
}ts
type Line = { done: boolean };
type Order = { readonly id: string; lines: Line[]; meta: { tag: string } };
export function renamed(order: Order): Order {
const copy = { ...order, id: "new", meta: { ...order.meta } };
copy.meta.tag = "renamed";
return copy;
}
export function closed(order: Order, extra: Line): Line[] {
const __la1 = order.lines; const __lr1: any[] = new Array(__la1.length); for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let line = __le1; __lr1[__li1] = (({ ...line })); }} const list = [...__lr1, extra];
for (const line of list) line.done = true;
return list;
}
export function retitled(order: Order): Order {
const copy = { ...order };
copy.meta = { tag: "retitled" };
copy.meta.tag = "retitled twice";
return copy;
}A field the copy is given in the literal ({ ...order, meta: { tag: "" } }), or by an assignment written as a statement of the block the copy is made in (copy.meta = { ... }), holds the copy's own value from there on; an assignment in a branch (if (fresh) copy.meta = ...) may not have run, so the field is still the caller's after it. A spread of something else after the parameter's ({ ...order, ...patch }) may replace some fields, but nothing says which: they stay the parameter's. structuredClone(order) copies all the way down (the feature pack's version returns a Result; the global one throws on a value it can't copy).
Lending a copy whole (f(mut({ ...order })), or a copy a helper hands back) is reported only for the fields the callee could write through, and the finding names them ("tags and notes still hold the caller's"). A field is not shared for writing when:
- the copy was given a value of its own for it (a field given the parameter's part as it is,
tags: o.tags, is still shared; one given a new list, map or set,lines: o.lines.slice(),byId: new Map(o.byId), shares only what its elements hold: see the next paragraph); - its written type holds no object (a primitive, a function), or is a
@cacheorMut<...>field; - nothing can be written through it as far down as its type is written: a
readonly T[],ReadonlyArray,ReadonlyMaporReadonlySetof such values, an object type whose properties are allreadonlyand of such types. A part shared on purpose (replaced whole, never changed in place) says so in the type, and the checker holds the code to it; - the callee's parameter type doesn't have it (
retitle(s: Mut<{ title: string }>)reaches onlytitle), or has it read-only there; - the callee, a function or a method of the program, never names it: where all it does with its
Mutparameter is name fields of it (doc.title,const { title } = doc, a test ofdocitself), the fields it doesn't name are out of its reach, so a lend toonlyTitle(doc: Mut<Doc>) { doc.title = "x"; }or toeditor.rename(mut(copy))is fine. A field it only gives a new value (doc.tags = []) is a new value for the copy's own slot, not a use of what it held. A callee that hands the parameter on whole, aliases it or indexes it may change anything. So may a method of a class that can be extended (exported, extended in its file or abstract): an override may run instead of the method written, so only a static method, or a method of a class nothing can extend, is read this way.
A type the checker can't open (a package's type, no annotation at all) may hold an object.
A field the copy was given a new list, map or set of (units: w.units.slice(), [...w.units], new Map(w.byId)) is the copy's own list: only its items are the caller's. So it stays in the finding only when the callee may change an item, as the whole program says. Changing the list itself is no change of the caller's data: splice, push, pop, shift, sort, reverse, an index written (w.units[0] = next), length = 0, a map's set and delete, a set's add and clear, and w.units = w.units.filter(...). A callee changes an item when it writes through one (in a for...of, in a callback such as forEach((u) => u.hp++), through a local, find(...)!.hp = 0, through what pop or splice hands back, through an inner list of a list of lists), hands an item or the list to a function that may change it (heal(mut(first)), units.forEach(heal)), hands the list to code the checker can't follow (a callback it was given, a function value read from a table), or returns an item or the list. The callee's parameter handed on whole (step(mut(w))) is followed into the functions it goes to, across files and around cycles of calls, and a spread copy the callee makes of it (const before = { ...w }) counts as the parameter. A function in a checked file whose parameter isn't declared Mut<...> changes nothing through it (this rule reports the function that does).
Where the analysis loses track of an item it counts as changed, so a callee that only reads its items in a way it doesn't follow is still reported: the item handed to a local function (place(p.cell) with const place = ... in the callee), spread into a new object ({ ...p, cell }), or put into another list. The finding names only the fields it couldn't clear. Copying the items too (units: w.units.map((u) => ({ ...u }))) or writing them read-only in the type settles it.
✅ Accepted: the callee changes only the new lists, not what they hold
✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Unit = { id: number; hp: number };
type Camp = { units: Unit[]; dead: Unit[]; name: string };
function cloneCamp(camp: Camp): Camp {
return { ...camp, units: camp.units.slice(), dead: [...camp.dead] };
}
function retire(camp: Mut<Camp>): void {
camp.units.sort((a, b) => b.hp - a.hp);
camp.units.pop();
camp.dead.length = 0;
}
export function previewRetire(camp: Camp): Camp {
const copy = cloneCamp(camp);
retire(mut(copy));
return copy;
}ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Unit = { id: number; hp: number };
type Camp = { units: Unit[]; dead: Unit[]; name: string };
function cloneCamp(camp: Camp): Camp {
return { ...camp, units: camp.units.slice(), dead: [...camp.dead] };
}
function retire(camp: Mut<Camp>): void {
camp.units.sort((a, b) => b.hp - a.hp);
camp.units.pop();
camp.dead.length = 0;
}
export function previewRetire(camp: Camp): Camp {
const copy = cloneCamp(camp);
retire(copy);
return copy;
}✅ Accepted: what the callee may write isn't shared
✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Board = { title: string; readonly marks: readonly number[]; cells: { done: boolean }[] };
function retitle(board: Mut<{ title: string }>): void {
board.title = "copy";
}
export function titled(board: Board): Board {
const copy = { ...board };
retitle(mut(copy));
return copy;
}ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Board = { title: string; readonly marks: readonly number[]; cells: { done: boolean }[] };
function retitle(board: Mut<{ title: string }>): void {
board.title = "copy";
}
export function titled(board: Board): Board {
const copy = { ...board };
retitle(copy);
return copy;
}Methods, parts handed out, and what an object keeps
What is reached through a borrowed value is borrowed, however it got there.
A method that changes its object is Rust's &mut self: calling it on a borrowed parameter changes the caller's object. The checker reads the method's body, across files and up the extends chain: it changes the object when it assigns a field (also through a local naming a part of it, or an element in a for...of over a field), calls a method of the object that does, calls a changing method on a field (this.items.push(...), a field of one of your classes whose method changes it), or lends the object or a part of it (wipe(mut<Cart>(this)), grow(mut(this.items))). The message spells out the chain. A method named like a collection's (clear, set, add) of one of your classes is decided by its body too. A method that only fills a field marked /** @cache */ changes nothing (Caches). A getter that changes its object is mutating-getter's, at the getter.
✕ Rejectedno-param-mutation
ts
export class Counter {
n = 0;
bump(): void {
this.n += 1;
}
}
export function bumpCounter(c: Counter): void {
c.bump();
}✅ Accepted: the function says it changes the counter, or works on its own
✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
export class Counter {
n = 0;
bump(): void {
this.n += 1;
}
}
export function bumpCounter(c: Mut<Counter>): void {
c.bump();
}
export function twice(): number {
const c = new Counter();
bumpCounter(mut(c));
c.bump();
return c.n;
}ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
export class Counter {
n = 0;
bump(): void {
this.n += 1;
}
}
export function bumpCounter(c: Mut<Counter>): void {
c.bump();
}
export function twice(): number {
const c = new Counter();
bumpCounter(c);
c.bump();
return c.n;
}A part handed out stays borrowed: Rust's fn peek(o: &Outer) -> &Inner. A function whose every return gives back a part of the same borrowed parameter (return o.inner, an element return order.lines[0], either side return first ? o.a : o.b or return firstLine(order) ?? order.lines[i], what another such function returns; a return undefined beside it is fine), and a method whose every return gives back its object or a part of it (return this.lines, return this.items.find(...), a builder's return this), hand out the argument itself; where some return gives a new list holding its objects (return order.lines.filter(...)), changing an object in that list is changing the argument: changing what the call returns changes the argument, and is reported where the argument is a borrowed parameter of the caller. What to write: a readonly return type (readonly Line[], Readonly<Inner>) where the caller should only read it, a copy ([...this.lines], { ...o.inner }) where it may change its own (what the copy's slots hold is still the argument's: Copies), or Mut in and Mut out where changing the part is the point: function peekMut(o: Mut<Outer>): Mut<Inner> { return mut(o.inner); }. A getter's result is a member read, so const lines = order.lines was already a part of order.
✕ Rejectedno-param-mutation
ts
type Inner = { value: number };
type Outer = { readonly inner: Inner };
function peek(o: Outer): Inner {
return o.inner;
}
export function reset(o: Outer): void {
const inner = peek(o);
inner.value = 0;
}✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Inner = { value: number };
type Outer = { readonly inner: Inner };
function peekMut(o: Mut<Outer>): Mut<Inner> {
return mut(o.inner);
}
export function reset(o: Mut<Outer>): void {
const inner = peekMut(mut(o));
inner.value = 0;
}ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
type Inner = { value: number };
type Outer = { readonly inner: Inner };
function peekMut(o: Mut<Outer>): Mut<Inner> {
return o.inner;
}
export function reset(o: Mut<Outer>): void {
const inner = peekMut(o);
inner.value = 0;
}What an object keeps. A method or constructor that keeps a borrowed parameter in its object (this.items.push(item), this.cart = cart, constructor(private readonly cart: Cart)), where the class's code changes what it keeps later, changes the caller's object long after the call. Rust would need a lifetime, or ownership. It is reported at the store, because the fix belongs to its parameter: declare it Mut<...>, so the caller lends it with mut(...) and sees that the object keeps and changes it, or keep a copy. Keeping a parameter and only reading it is fine, and so is setting an event-handler slot of a platform object kept that way (this.port.onmessage = ...).
✕ Rejectedno-param-mutation
ts
type Item = { value: number };
export class Registry {
private readonly items: Item[] = [];
add(item: Item): void {
this.items.push(item);
}
zero(): void {
for (const item of this.items) item.value = 0;
}
}✓ Accepted0 diagnostics
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";
type Item = { value: number };
export class Registry {
private readonly items: Mut<Item>[] = [];
add(item: Mut<Item>): void {
this.items.push(item);
}
zero(): void {
for (const item of this.items) item.value = 0;
}
}
export class Viewer {
private readonly item: Item;
constructor(item: Item) {
this.item = item;
}
show(): string {
return String(this.item.value);
}
}Drawing contexts
A CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D parameter is a sink: drawing on it (g.fillStyle = ..., g.lineWidth = 2) is what it is passed for, like an event or a builder. It counts as owned, without Mut<...>:
✓ Accepted0 diagnostics
ts
export function drawBadge(g: CanvasRenderingContext2D, label: string): void {
g.fillStyle = "#222";
g.font = "12px sans-serif";
g.fillText(label, 4, 12);
}One finding per parameter
All the changes to one parameter are one finding, at the first: "Changes parameter cart, which belongs to the caller: here and in 3 other places (lines 12, 14, 20)". The fix (declare it Mut<...>, or work on a copy) is one decision for the parameter, not one per line.
Methods of a package's classes aren't known to change their object, so g.moveTo(...) on a graphics object from a package isn't counted as a change; only assignments and the changing methods of arrays, maps and sets are (g.x = 1, g.points.push(p)). A function that draws with such an object takes it Mut<...> to say so. Methods of your own classes are read (above).
Allowed: changing a copy's own slots ([...x], x.slice(), { ...x }: what they hold is still the caller's, Copies), anything of structuredClone(x), reassigning the parameter variable itself (count += 1), a reduce accumulator, rest parameters (...args is a fresh array), this in class methods, and fields marked /** @cache */ in the parameter's type (a memo the function fills while it only reads the rest: Caches).
Quick fixes: Use toSorted() / toReversed() (when the result is used; not for splice, which returns the removed items where toSpliced returns the rest) · Update a copy: x = { ...x, field: … }, only where x's type is a plain object's declared in the file (an object type, or an alias or interface of one, without methods): an array or a class instance spread into an object is another kind of value · Declare that this function changes the elements of x: readonly Mut<…>[], for a change to an element of a list written T[] or readonly T[] · Declare that this function changes x: Mut<…>.
What the rule can't see:
- A method declared in an interface or an object type (
repo.save()withrepo: Repo): a slot has no body to read, so a call through it isn't a change, whatever the class behind it does. TypeScript's own way to say "this changes the object" in a signature, athis: Mut<Repo>parameter, would ask every call to writemut(repo).save(), also on what the caller owns. The same for a subclass's override that changes the object where the method it overrides doesn't: a call is followed into the class its receiver is declared with. - A part handed out by
mapwhose callback returns its argument (lines.map((l) => l),Array.from(lines, (l) => l)):mapis taken to make new objects. And what a project method hands back of an argument other than its receiver isn't followed; a function's is. - What is kept somewhere other than the object's own fields: in a collection of a
Mutparameter (registry.items.push(item)), in a closure stored for later, or changed by code outside the class through a field it exposes. Module-level state isno-mutable-global's. - Calls through what a call returns, twice over (
peek(peek2(o))): one call is followed. - A copy kept, or handed back by a method: a copy stored in the object (
this.saved = { ...order }, thenthis.saved.meta.tag = ...later), and a method returning a copy of a part of its object (snapshot() { return { ...this.state }; }) are not followed into later changes. A copy of a part ofthismade and changed in the method itself is: the method changes its object. - Which spread a field comes from when several of the parameters are spread (
Object.assign({}, order, patch)): the change is reported on the last of them. - A new container's elements whose type isn't written: a copy of a list of numbers lent to a parameter declared with a list of objects is still reported, since nothing says the copy holds numbers.
- Changes made by functions you pass the parameter to that don't declare
Mut<...>(a package's, or a project function that changes its parameter without saying so, which is reported there). - TypeScript's own
readonlyhole: areadonlyobject can be assigned to a type withoutreadonly, through which it can then be changed (const p: { readonly x: number } = ...; const q: { x: number } = p; q.x = 1compiles).readonly-droppedrefuses that binding where both types are written in the file; through an imported type it still compiles.