unthrown icon indicating copy to clipboard operation
unthrown copied to clipboard

`.isOk()` / `.isErr()` / `.isDefect()` methods don't narrow (return `boolean`)

Open btravers opened this issue 5 months ago • 1 comments

Summary

The instance methods .isOk() / .isErr() / .isDefect() return boolean and do not narrow. The standalone isOk(r) / isErr(r) / isDefect(r) functions do narrow. The dual API is a sharp, repeat-bite footgun — especially for codebases migrating from neverthrow, where the methods narrow.

Where

isOk(): boolean;
isErr(): boolean;
isDefect(): boolean;

vs the standalone guards:

declare function isOk<T, E>(r: Result<T, E>): r is OkView<T, E>;
declare function isErr<T, E>(r: Result<T, E>): r is ErrView<E, T>;
declare function isDefect<T, E>(r: Result<T, E>): r is DefectView<T, E>;

Why it matters

The natural, neverthrow-shaped pattern silently fails to compile away the other variants:

if (result.isErr()) {
  result.error; // ❌ not narrowed — `.error` not accessible
}

In a downstream consumer this is the single most-repeated mistake (it's documented as a "common mistake" in that repo's agent rules, and a code-review bot flagged a doc example that misused .isErr() as a guard). Anyone coming from neverthrow walks straight into it.

Proposal

Type the methods as type predicates so they narrow on their own:

isOk(): this is OkView<T, E>;
isErr(): this is ErrView<E, T>;
isDefect(): this is DefectView<T, E>;

This collapses the two parallel APIs into one and eliminates a whole class of mistakes. If there's a deliberate reason to keep the methods non-narrowing (e.g. steering users toward exhaustive match), documenting that rationale next to the standalone guards would at least make the split intentional rather than surprising.

btravers avatar Jun 26 '26 14:06 btravers

Adjacent finding from the temporal-contract migration (btravstack/temporal-contract#263): even once you switch to the free-function guards, a second narrowing gap remains because Result<T, E> always includes the Defect variant.

function use(r: Result<{ n: number }, MyErr>) {
  if (isErr(r)) return handle(r.error);
  // ❌ r is `Ok | Defect` here — `.value` doesn't exist on `Defect`
  return r.value.n;
}

For an internally-produced result that is known to never be a defect (built only from ok/err), there's no built-in way to discharge the impossible-Defect case, so call sites need a manual if (!isOk(r)) throw r.cause; guard before .value. We ended up adding our own assertion helper:

function assertNoDefect<T, E>(r: Result<T, E>): asserts r is OkView<T, E> | ErrView<E, T> {
  if (isDefect(r)) throw r.cause;
}

A built-in assertNoDefect (or an unwrapOrThrowDefect-style narrowing) would remove this boilerplate and pairs naturally with the method-narrowing fix in this issue.

btravers avatar Jun 26 '26 14:06 btravers