Skip to content

must-use-result ​

A Result is ignored, so its error is silently dropped.

Why: like Rust's #[must_use]: a failure you never look at is a bug waiting to happen. Applies to functions with a declared Result (or Promise<Result>) return type, also written as a type alias (type Loaded = Promise<Result<User, LoadError>>, an alias of an alias, an imported one, a generic one given its arguments: Loaded<User>), to those without a declared type that return err(...) (also as a branch: return ok ? value : err(...)) or another such function's Result, to unsafe(...), to parseJson/validate, and to a feature pack's safe versions (readFileSync of @evobug_com/safe-ts-feature-node/fs), not to those that only return an Option (get(params, k)). Nor to a type of another kind that happens to be named Result in the function's file (std's T | Err<E> is the one that counts): a match(...) run for its handlers' effects, as a statement, is fine. Guide: Errors.

✕ Rejectedmust-use-result
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";

type SendError = Enum<{ InvalidAddress: { to: string } }>;
const SendError = constructors<SendError>();

function sendEmail(to: string): Result<void, SendError> {
  return to.includes("@") ? undefined : err(SendError.InvalidAddress({ to }));
}

export function welcome(user: string): void {
  sendEmail(user);
}
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";

type SendError = Enum<{ InvalidAddress: { to: string } }>;
const SendError = constructors<SendError>();

function sendEmail(to: string): Result<void, SendError> {
  return to.includes("@") ? undefined : err(({ tag: "InvalidAddress", to } satisfies SendError as SendError));
}

export function welcome(user: string): void {
  sendEmail(user);
}
✓ Accepted0 diagnostics
ts
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, q, type Result } from "@evobug_com/safe-ts-std/result";

type SendError = Enum<{ InvalidAddress: { to: string } }>;
const SendError = constructors<SendError>();

function sendEmail(to: string): Result<void, SendError> {
  return to.includes("@") ? undefined : err(SendError.InvalidAddress({ to }));
}

// Handle it,
export function welcome(user: string): string {
  const sent = sendEmail(user);
  return isErr(sent) ? match(sent.error, { InvalidAddress: ({ to }) => `no such address: ${to}` }) : "sent";
}

// or pass it on,
export function welcomeOrFail(user: string): Result<void, SendError> {
  q(sendEmail(user));
  return undefined;
}

// or say explicitly that it doesn't matter.
export function welcomeIfPossible(user: string): void {
  void sendEmail(user);
}
ts
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { err, isErr, q, type Result } from "@evobug_com/safe-ts-std/result";

type SendError = Enum<{ InvalidAddress: { to: string } }>;
const SendError = constructors<SendError>();

function sendEmail(to: string): Result<void, SendError> {
  return to.includes("@") ? undefined : err(({ tag: "InvalidAddress", to } satisfies SendError as SendError));
}

// Handle it,
export function welcome(user: string): string {
  const sent = sendEmail(user);
  return isErr(sent) ? match(sent.error, { InvalidAddress: ({ to }) => `no such address: ${to}` }) : "sent";
}

// or pass it on,
export function welcomeOrFail(user: string): Result<void, SendError> {
  { const __q1 = sendEmail(user); if (__q1 instanceof __qErr) return __q1; __q1; }
  return undefined;
}

// or say explicitly that it doesn't matter.
export function welcomeIfPossible(user: string): void {
  void sendEmail(user);
}

Quick fixes: Propagate the error with q(…) (in functions returning Result) · Discard explicitly with void.

Promise chains: load().then(handle) hands the Result to handle, so it counts as used (an unhandled rejection is floating-rejection's job). .catch(...) and .finally(...) resolve to the same Result, so load().catch(log); still drops it. A Result-returning call that a .then/.catch callback returns, in a chain whose value nobody reads, is reported too.

Calls it follows ​

The call is followed to the function it runs, in this file or another, the same way for must-use-result, unhandled-failure and floating-rejection:

  • a function declaration, or an arrow or function expression in a const, at module level or nested, called by name, through an import, a namespace import (requests.load()) or await import(...);
  • a method of a module-level object literal or class, and a member of a module-level object that names a function (const api = { load, save: store.save }, then api.load());
  • a member of the object a followed function returns: useCart().load(), const cart = useCart(); cart.load(), const { load } = useCart(); load(). The member may be written in the returned literal (return { load: async () => ... }) or name a function declared in the function (return { load }). This is how composables and Pinia stores are followed;
  • the function a factory returns: const save = makeSaver("title"); save(), also when makeSaver is in another file and save is exported from there;
  • Pinia stores: defineStore("cart", () => { ...; return { load } }) (a setup store) and defineStore("cart", { actions: { load() {...} } }) (an options store). useCartStore() hands back the setup function's members, or the actions;
  • a copy: const save = store.save, const { save } = store, a class field handler = save, also exported and imported elsewhere, and save.call(...), save.bind(...)(...);
  • a method of a value declared with any written form of its class's type, through the aliases every rule opens: a generic alias (deps: Services<Repo>, also imported, also destructured: ({ repo }: Services<Repo>)), a generic interface (box: Box<Repo>), Readonly, Partial, Required, Pick, Omit, NonNullable, Awaited, std's Option and Mut of one, a union with undefined or null (through ?. or after a check), a Map's get (byName.get(id)?.check()), an item of an array or tuple (repos[0]?.check(), pair[0], const [head] = repos), a Record's or an index signature's value, what iterating a Map or Set gives (for (const [, repo] of byName), byName.values(), .entries(), .keys()), await of a Promise<Repo> and the parameter of its .then((repo) => ...);
  • an optional call like the plain one: repo?.check(id), deps.repo?.check(id), this.hooks?.flush().

A function used by name is the arrow that calls it. list.forEach(check) drops each Result the way list.forEach((item) => check(item)) does, and both are reported: forEach (also filter, some, every, find, sort) doesn't keep what its callback returns, and neither does a timer (setTimeout(check, 5, "x"), queueMicrotask, requestAnimationFrame), a listener (el.addEventListener("click", () => check("x")), emitter.on(...)) or a server's handler. map, flatMap and reduce keep it, so list.map(check) is a list of Results, not a dropped one, unless the list itself is dropped: list.map(check); as a statement, and await Promise.all(list.map(save)); (also Promise.all([save(a), save(b)])), drop every one.

✕ Rejectedmust-use-result
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";

export type SaveError = Enum<{ Empty: {} }>;
export const SaveError = constructors<SaveError>();

function save(note: string): Result<void, SaveError> {
  return note === "" ? err(SaveError.Empty()) : undefined;
}

export function saveAll(notes: readonly string[]): void {
  notes.forEach(save);
}
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";

export type SaveError = Enum<{ Empty: {} }>;
export const SaveError = constructors<SaveError>();

function save(note: string): Result<void, SaveError> {
  return note === "" ? err(({ tag: "Empty" } satisfies SaveError as SaveError)) : undefined;
}

export function saveAll(notes: readonly string[]): void {
  { const __la1 = notes; const __lf1_0: any = save; for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { __lf1_0(__le1, __li1, __la1); }} }
}
✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, q, type Result } from "@evobug_com/safe-ts-std/result";

export type SaveError = Enum<{ Empty: {} }>;
export const SaveError = constructors<SaveError>();

function save(note: string): Result<void, SaveError> {
  return note === "" ? err(SaveError.Empty()) : undefined;
}

export function saveAll(notes: readonly string[]): Result<void, SaveError> {
  for (const note of notes) {
    q(save(note));
  }
  return undefined;
}
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { err, q, type Result } from "@evobug_com/safe-ts-std/result";

export type SaveError = Enum<{ Empty: {} }>;
export const SaveError = constructors<SaveError>();

function save(note: string): Result<void, SaveError> {
  return note === "" ? err(({ tag: "Empty" } satisfies SaveError as SaveError)) : undefined;
}

export function saveAll(notes: readonly string[]): Result<void, SaveError> {
  for (const note of notes) {
    { const __q1 = save(note); if (__q1 instanceof __qErr) return __q1; __q1; }
  }
  return undefined;
}

❌ Rejected: a member of the object a function returns

✕ Rejectedmust-use-result
ts
import { err, type Result } from "@evobug_com/safe-ts-std/result";

export function createCart() {
  const items: string[] = [];
  return {
    add(item: string): Result<number, string> {
      if (items.includes(item)) return err(`${item} is already in the cart`);
      items.push(item);
      return items.length;
    },
  };
}

export function fill(): void {
  const cart = createCart();
  cart.add("apple");
}

The same for a Pinia store, in any file that uses it:

ts
// stores/cart.ts
export const useCartStore = defineStore("cart", () => {
  const items = ref<Item[]>([]);
  async function load(): Promise<Result<void, LoadError>> {
    items.value = q(await fetchItems());
    return undefined;
  }
  return { items, load };
});

// Cart.vue
const cart = useCartStore();
await cart.load(); // must-use-result: the LoadError is dropped
cart.load().catch(() => {}); // must-use-result too: `.catch` resolves to the same Result

A Result kept in a local ​

A Result kept in a local is dropped too when, on some path from there to the end of the function, nothing looks at it, or a new value replaces it first. Kept is also each call of a branch (const r = flag ? save(1) : save(2), cached ?? (await load()), through parentheses and await), an optional call (const r = repo?.check(id)), and each element of const [a, b] = await Promise.all([save(1), save(2)]) (or allSettled) over a list written in place, in the binding at its place. Logging it (console.log(r), any console method) or turning it into text (String(r), `${r}`, r + "", JSON.stringify(r), r.toString()) isn't looking at it, kept in a local or written in place (console.log(save(order))). For a feature pack's safe version, comparing its Result with undefined or null isn't looking at it either: std's Result is T | Err<E>, so in getItem(localStorage, k) !== undefined an Err passes for a stored value; unwrap it first (q(...), isErr(...)). Your own function's Result<void, E> tested with r === undefined does look at it (only an Ok is undefined). A promise kept in a const and read once in the next statement is the call written there: const p = saveAsync(x); const r = await p; keeps the Result in r, and const p = saveAsync(x); await p; drops it.

❌ Rejected: the failure is logged, and the function goes on as if it saved

✕ Rejectedmust-use-result
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";

export type SaveError = Enum<{ Empty: {} }>;
export const SaveError = constructors<SaveError>();

function save(note: string): Result<void, SaveError> {
  return note === "" ? err(SaveError.Empty()) : undefined;
}

export function saveAndCount(notes: readonly string[]): number {
  let saved = 0;
  for (const note of notes) {
    const r = save(note);
    console.log(r);
    saved++;
  }
  return saved;
}
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";

export type SaveError = Enum<{ Empty: {} }>;
export const SaveError = constructors<SaveError>();

function save(note: string): Result<void, SaveError> {
  return note === "" ? err(({ tag: "Empty" } satisfies SaveError as SaveError)) : undefined;
}

export function saveAndCount(notes: readonly string[]): number {
  let saved = 0;
  for (const note of notes) {
    const r = save(note);
    console.log(r);
    saved++;
  }
  return saved;
}
✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";

export type SaveError = Enum<{ Empty: {} }>;
export const SaveError = constructors<SaveError>();

function save(note: string): Result<void, SaveError> {
  return note === "" ? err(SaveError.Empty()) : undefined;
}

export function saveAndCount(notes: readonly string[]): number {
  let saved = 0;
  for (const note of notes) {
    const r = save(note);
    if (!isErr(r)) saved++;
  }
  return saved;
}
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";

export type SaveError = Enum<{ Empty: {} }>;
export const SaveError = constructors<SaveError>();

function save(note: string): Result<void, SaveError> {
  return note === "" ? err(({ tag: "Empty" } satisfies SaveError as SaveError)) : undefined;
}

export function saveAndCount(notes: readonly string[]): number {
  let saved = 0;
  for (const note of notes) {
    const r = save(note);
    if (!isErr(r)) saved++;
  }
  return saved;
}

What looks at it: a test (isErr(r), isOk(r), match(r, ...), q(r), r === undefined, if (r), typeof r), returning it, reading a member of it (TypeScript allows that only after a test), void r (discarded on purpose), and handing it on: an argument of a call (other than console and String), an element of an object or array literal (return { saved }, results.push(r)), a value assigned to a field, a function written inside that reads it (it looks at it later). An exported module-level const is handed on to its importers.

Paths are followed (how), with three things that aren't a drop:

  • An exception. A throw, or a point of a try that goes to its catch: the failure leaves another way, and the catch (or the caller) deals with it.
  • An early return before the code that looks at it. if (signal.aborted) return; or if (isErr(other)) return other; written before if (isErr(r)) leaves the work the Result was part of: only an end of the function after every look counts. A Result looked at on one branch and not on the path that goes on to the end is reported (if (strict) return !isErr(r); return true;).
  • One test of several. !isErr(a) && !isErr(b) doesn't look at b when a failed; the test answers for both, and counts as looking at each.

Reported at the call, as for a dropped call, when the function returns a Result; for an async function, when it is awaited (an unawaited promise kept in a local is floating-rejection's).

What the rule can't see: a return type written as an alias whose body has to be computed rather than substituted (a conditional or mapped type, typeof, an indexed access: the alias is left unopened, so the function isn't taken to return a Result), a function without a declared type whose Result comes from somewhere other than err(...) or a followed call (undeclared-return-type lists those), and a function reached through a value the checker doesn't follow: a method an interface or a union declares (a contract, not a body: one declared with the class is followed, as are deps.repo.check() with deps: Deps and the written forms above), a value of a type parameter of the function it is in, a type that has to be computed (a conditional or mapped type), an object built and changed elsewhere, a function stored in a ref, reactive(), a Map or an object literal inside a function. In a chain it sees calls a callback returns, and a function passed by name (.then(save)), not a Result value the callback returns (.then((r) => r)). A kept Result is followed in the local it is put in, not through a copy (const copy = r is handing it on), not through an object a function returns (const { result } = pair(): what result is, only pair's return type says), and not through a promise chain kept in a local (const r = await save().catch(log)), nor along a chain or a list kept in a const first (const p = save(); await p.finally(done), const list = [save(1)]; await Promise.all(list)). Logging is console's methods only: a logger of the project (logger.info(r)) is a function it is handed to.

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