unthrown icon indicating copy to clipboard operation
unthrown copied to clipboard

.match({ err }) signature change is invisible to the type checker (silent runtime break)

Open btravers opened this issue 4 months ago • 0 comments

Summary

In 5.0 the err handler of .match({ ok, err, defect }) receives the ts-pattern matcher instead of the error. That is a good change, but the 4.x call shape still compiles whenever the handler throws — and then misbehaves at runtime.

Reproduction

// 4.x code — compiles cleanly under 5.0.0-beta.4
return result.match({
  ok: (value) => value,
  err: (error) => {
    throw error;
  },
  defect: (cause) => {
    throw cause;
  },
});

A throwing handler returns never, and never vacuously satisfies the M extends ExhaustiveMatch<unknown> constraint. So tsc is happy, and at runtime the handler throws the matcher object instead of the error.

Impact

Found while upgrading a large monorepo from 4.3.0. This exact shape was our bridge from an AsyncResult to a job runner's throw-based contract — a generic helper of the form:

async function toRunnerPromise<T, E extends Error = never>(
  r: AsyncResult<T, E>,
): Promise<T> { /* the match above */ }

The runner distinguishes a thrown "terminal" error object from any other thrown value, retrying the latter. After the upgrade every modeled, deliberately non-retryable error became an unrecognised thrown value — so jobs that were supposed to fail fast retried indefinitely.

The whole repo type-checked green. Only an integration test asserting the job reached a failed state caught it, and only after diffing against a 4.3.0 baseline to prove it was a regression rather than a flake.

This is the one 5.0 break that is not mechanically discoverable: every other renamed combinator (mapErr → mapErrCases etc.) fails loudly because the old name no longer exists.

Suggested fix

Any one of these would have caught it:

  1. Rename the option to errCases:. Simplest and loudest — every other Err combinator gained the …Cases suffix, so this is also more consistent. The old err: key then becomes an excess-property error.
  2. Brand ErrMatcher<E> with a phantom property that a TaggedError cannot structurally satisfy, so a 1-arg (error) => … cannot bind.
  3. Exclude never from the M constraint, e.g. M extends ExhaustiveMatch<unknown> & ([M] extends [never] ? ErrorMessage : unknown).

Option 1 seems best: it is a compile error rather than a subtle inference fix, and it matches the naming the rest of the release already adopted.

Environment

btravers avatar Jul 27 '26 16:07 btravers