unthrown icon indicating copy to clipboard operation
unthrown copied to clipboard

ExhaustiveMatch can't be satisfied behind a generic E, even with P._

Open btravers opened this issue 4 months ago • 3 comments

Summary

ExhaustiveMatch cannot be satisfied inside a generic function where the error type is still a type parameter, even with the universal P._ pattern.

Reproduction

import { type AsyncResult, P } from "unthrown";

export async function toRunnerPromise<T, E extends Error = never>(
  asyncResult: AsyncResult<T, E>,
): Promise<T> {
  const result = await asyncResult;
  return result.match({
    ok: (value) => value,
    err: (matcher) =>
      matcher.with(P._, (error) => {
        throw error;
      }),
    defect: (cause) => {
      throw cause;
    },
  });
}
TS2322: Type 'InvertPatternForExclude<UnknownPattern, WithDefault<ExtractPreciseValue<E,
        InvertPattern<UnknownPattern, E>>, E>> extends infer excluded ? Match<...> : never'
        is not assignable to type 'ExhaustiveMatch<unknown>'.
TS2322: Type 'unknown' is not assignable to type 'T'.

The same body compiles once E is a concrete union.

Why this matters

P._ matches everything by construction, so a builder terminated with a P._ arm is exhaustive regardless of what E turns out to be. Deferring that judgement until E is instantiated means no generic helper can wrap .match — which is exactly the kind of code a library boundary helper is (a job-runner bridge, a generic HTTP responder, a test utility).

Workaround

The narrowing guards work and are arguably clearer at a boundary that is leaving the Result world anyway:

const result = await asyncResult;
if (result.isErr()) throw result.error;
if (result.isDefect()) throw result.cause;
return result.value;

That is what we shipped. But it means the …Cases / match API is effectively unavailable to generic code, which is worth documenting even if the inference is hard to fix.

Suggested direction

Special-case a builder whose remaining type is unknown/unresolved but which contains a P._ arm, or relax ExhaustiveMatch so an unresolved E is accepted rather than rejected.

Environment

btravers avatar Jul 27 '26 16:07 btravers

Re-tested against 5.0.0-beta.5 — this one still reproduces. The other four are confirmed fixed (thank you): errCases makes the old .match shape an excess-property error, ts-pattern is now a peer ^5 and resolves to our copy, the getOrThrow gate prints its branded message, and MIGRATION.md is there.

Same generic helper, updated to the new errCases key:

import { type AsyncResult, P } from "unthrown";

export async function toRunnerPromise<T, E extends Error = never>(
  asyncResult: AsyncResult<T, E>,
): Promise<T> {
  const result = await asyncResult;
  return result.match({
    ok: (value) => value,
    errCases: (matcher) =>
      matcher.with(P._, (error) => {
        throw error;
      }),
    defect: (cause) => {
      throw cause;
    },
  });
}
example.ts:23:3: error typescript(TS2322): Type 'unknown' is not assignable to type 'T'.
example.ts:26:7: error typescript(TS2322): Type 'InvertPatternForExclude<AnyPattern, WithDefault<ExtractPreciseValue<E,
  InvertPattern<AnyPattern, E>>, E>> extends infer excluded ? Match<...> : never'
  is not assignable to type 'ExhaustiveMatch<unknown>'.

Only difference from beta.4 is that the pattern type is now spelled AnyPattern rather than UnknownPattern; the assignability failure is unchanged. It still compiles fine once E is a concrete union.

We're staying on the isErr() / isDefect() guards for that helper, which is honestly fine at a boundary that leaves the Result world anyway — so no urgency from our side. Flagging it only because the issue was closed with the batch.

Environment: [email protected], TypeScript 7.0.1-rc, strict: true.

btravers avatar Jul 27 '26 18:07 btravers

Reopening is right — the batch Closes was over-eager on this one: #147 documented the limitation (guide section + a type-d regression test pinning it) but did not fix it. I've now dug into whether it is fixable at all on unthrown's side. Short answer: no, not without giving up the exhaustiveness guarantee for concrete code. The fix belongs upstream in ts-pattern.

Root cause (verified against beta.5 / ts-pattern 5.9): over an unresolved E, the builder returned by matcher.with(P._, …) types its .exhaustive as a deferred conditional — DeepExclude…<E, InvertPatternForExclude<AnyPattern, …E…>> extends infer remaining ? ([remaining] extends [never] ? Exhaustive : NonExhaustiveError<remaining>) : …. TS can only prove a deferred conditional assignable to a target when every branch is, and the NonExhaustiveError branch is not callable — so the builder fails ExhaustiveMatch's exhaustive: (...args: never[]) => unknown requirement, and the constraint failure cascades into MatchOut<M> collapsing (the Type 'unknown' is not assignable to type 'T' you see). Notably .run() itself types fine generically; it is only the exhaustiveness proof that can't resolve.

Why unthrown can't relax it: a resolved non-exhaustive builder over a concrete E also has exhaustive: NonExhaustiveError<…>. The type system gives us no way to distinguish "deferred because E is still a type parameter" from "resolved and genuinely missing a case" — any constraint loose enough to admit the former admits the latter, which reopens the blanket-handling hole for all concrete code. (The structural escape hatch — hand-rolling { exhaustive, run } — technically works in generic code, but it's strictly worse than the guards.)

The viable fix is upstream: for the universal patterns (P._ / P.any) exhaustiveness does not depend on the input type at all — the inverted pattern is unknown regardless of i. If ts-pattern special-cased the universal pattern to short-circuit remaining-cases to never without evaluating the input-dependent ExtractPreciseValue chain, the conditional would resolve even when i is an unresolved type parameter, and this helper would compile as written. Happy to file that as a feature request on gvergnaud/ts-pattern with the minimal repro.

Until/unless that lands: the isOk()/isErr()/isDefect() guards stay the sanctioned pattern for code generic in E (it's what unthrown's own interop bridges and @unthrown/orpc use, for exactly this reason). Keeping this issue open as the tracking issue for the limitation.

btravers avatar Jul 27 '26 21:07 btravers

Update — superseding my earlier analysis. "Not fixable on unthrown's side" was true while matching was delegated to ts-pattern; we've instead removed that premise: #151 replaces the ts-pattern peer with a built-in matcher (same .with / tag / P call-site shape), whose catch-all arm is a state transition to Remaining = never rather than a deferred exclusion — so .with(P._, …) is provably exhaustive even over an unresolved generic E.

Your exact repro is now a positive type-d test: resultToActivityPromise<T, E extends ApplicationFailure> compiles as originally written (modulo errCases). Tag arms alone over generic E remain correctly rejected. No upstream ts-pattern change needed — the issue closes with #151.

btravers avatar Jul 27 '26 22:07 btravers