Skip to content

union-tag-write ​

A write to a property through a value whose written type is a union of object types, where the members disagree on that property's type (kind: "mason" in one, kind: "archer" in the other). On by default, as an error.

Why: TypeScript lets a property of a union take what any member's property takes, so unit.kind = "archer" compiles on a Mason | Archer, also when the object is a mason. The object then says it is an archer while it has a mason's fields, and every switch on kind after it takes the wrong branch. Mut can't refuse it: a { readonly unit: Mason } lent where { readonly unit: Mason | Archer } is asked is fine for reading, and the write is the callee's. Rust has no such write: an enum's variant changes only by assigning a whole new value. Guide: State without globals.

✕ Rejectedunion-tag-write
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";

type Mason = { kind: "mason"; stone: number };
type Archer = { kind: "archer"; arrows: number };
type Slot = { unit: Mason | Archer };

export function retrain(slot: Mut<Slot>): void {
  slot.unit.kind = "archer";
}

✅ Accepted: a new object of the member it becomes

✓ Accepted0 diagnostics
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";

type Mason = { kind: "mason"; stone: number };
type Archer = { kind: "archer"; arrows: number };
type Slot = { unit: Mason | Archer };

export function retrain(slot: Mut<Slot>): void {
  slot.unit = { kind: "archer", arrows: 0 };
}

export function quarry(slot: Mut<Slot>): void {
  const unit = slot.unit;
  if (unit.kind === "mason") unit.stone += 1;
}

A property every member types the same (since: number in both) can be written: the object stays the member it is. Narrow the union first (a tag test, is(...), match) and TypeScript types the write by that member alone.

What the rule can't see ​

  • A value without a written type: const unit = slot.unit and then unit.kind = ...; the checker reads the types written in the file (a parameter's, a local's annotation, a field's, and members of an object type, an alias or an interface of the file, Readonly<...> and Mut<...> looked through). A type declared in another file isn't followed.
  • A union built by a generic, a mapped or a conditional type, or an interface that extends another.
  • A narrowed value written through its union's name: if (unit.kind === "mason") unit.kind = "mason" is reported, though it changes nothing.

Related: no-param-mutation, covariant-alias; guide: State without globals.

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