♻️ Adopt the three-overload matcher

strict/widened each take the exhaustive/fallback pattern shape in three
overloads ordered ExhaustiveLoose -> Fallback -> Handlers. TypeScript reads
the first overload for the object-literal popup (_?, a, b) and the last for
the missing-key error, so autocomplete and the error message are tuned
independently. The fallback is a pattern shape, not a factory, so the four
getPrimitiveUnionMatcher* factories collapse to two.

src/index.ts re-exports the two factories; the prototype scratch files that
explored the alternatives are removed.
This commit is contained in:
tmu committed 2026-09-17 20:59:09 +00:00
1 parent 02634f41de
commit 165bd9e3df
3 files changed
+373 -270

No files matched your search

+67 -59
View File
@@ -1,71 +1,79 @@
import type { Simplify, ValueOf } from "type-fest";
import type { ValueOf } from "type-fest";
type UnaryFn<T, R> = (shape: T) => R;
// ============================================================================
// ✔️ Exhaustive
// ❌ ReturnsStrict
// ============================================================================
type PatternPrimitiveUnion<R, T extends string | number> = {
[K in T]: UnaryFn<K, R>;
// `Extract` drops optional handlers (`undefined`) so `PatternReturns` also works
// when `P`'s constraint has optional keys.
type PatternReturns<P> = ReturnType<
Extract<ValueOf<P>, (...args: never[]) => unknown>
>;
type Handlers<R, T extends string | number> = { [K in T]: UnaryFn<K, R> };
// Fallback form: `_` is a required key, the T-keys are optional.
type Fallback<R, T extends string | number> = Partial<Handlers<R, T>> & {
_: UnaryFn<T, R>;
};
type PatternReturns<
P extends Record<string | number, UnaryFn<never, unknown>>,
> = ReturnType<ValueOf<P>>;
// Completion form: T-keys required, `_` optional. Overload #1, because
// TypeScript takes the *first* overload as the contextual type for the popup.
type ExhaustiveLoose<R, T extends string | number> = Handlers<R, T> & {
_?: UnaryFn<T, R>;
};
export const getPrimitiveUnionMatcherW: <T extends string | number>() => <
P extends PatternPrimitiveUnion<unknown, T>,
>(
pattern: Simplify<P>,
) => UnaryFn<T, PatternReturns<P>> = () => (pattern) => (shape) =>
// Rewrite not to use any is possible, was evaluated and solutions were
// more complex than the current solution.
// The `P`-constraints are deliberately *closed* (no index signature): that is
// what makes the excess-property check reject keys outside `T`/`_`.
type ExhaustiveShape<T extends string | number> = Handlers<unknown, T> & {
_?: UnaryFn<T, unknown>;
};
type FallbackShape<T extends string | number> = Partial<
Handlers<unknown, T>
> & {
_: UnaryFn<T, unknown>;
};
// oxlint-disable-next-line typescript/no-explicit-any typescript/no-unsafe-type-assertion
(pattern[shape] as any)(shape);
// Strict returns: one common `R`. Overload order is load-bearing:
// #1 ExhaustiveLoose -> autocomplete `_?, a, b`
// #2 Fallback -> accepts a partial pattern
// #3 Handlers (last) -> "Property 'b' is missing" is the reported error
interface StrictFn<T extends string | number> {
<R>(pattern: ExhaustiveLoose<R, T>): UnaryFn<T, R>;
<R>(pattern: Fallback<R, T>): UnaryFn<T, R>;
<R>(pattern: Handlers<R, T>): UnaryFn<T, R>;
}
// ============================================================================
// ✔️ Exhaustive
// ✔️ ReturnsStrict
// ============================================================================
export const getPrimitiveUnionMatcher: <T extends string | number>() => <R>(
pattern: Simplify<PatternPrimitiveUnion<R, T>>,
) => UnaryFn<T, R> = getPrimitiveUnionMatcherW;
// Widened returns: the union of every handler's return type. `P` is the whole
// parameter (not an intersection), so its closed constraint both supplies the
// contextual/autocomplete type and enforces the excess-property check.
interface WidenedFn<T extends string | number> {
<P extends ExhaustiveShape<T>>(
pattern: P & (keyof P extends T | "_" ? unknown : never),
): UnaryFn<T, PatternReturns<P>>;
<P extends FallbackShape<T>>(
pattern: P & (keyof P extends T | "_" ? unknown : never),
): UnaryFn<T, PatternReturns<P>>;
<P extends Handlers<unknown, T>>(
pattern: P & (keyof P extends T | "_" ? unknown : never),
): UnaryFn<T, PatternReturns<P>>;
}
// ============================================================================
// ❌ Exhaustive
// ✔️ ReturnsStrict
// ============================================================================
type PatternPrimitiveUnionPartial<R, T extends string | number> =
| PatternPrimitiveUnion<R, T>
| (Partial<PatternPrimitiveUnion<R, T>> & {
_: UnaryFn<T, R>;
});
type HandlerMap = Record<string | number, UnaryFn<never, unknown> | undefined>;
export const getPrimitiveUnionMatcherPartial: <T extends string | number>() => <
R,
>(
pattern: Simplify<PatternPrimitiveUnionPartial<R, T>>,
) => UnaryFn<T, R> = () => (pattern) => (shape) =>
// Rewrite not to use any is possible, was evaluated and solutions were
// more complex than the current solution.
const dispatch =
(pattern: HandlerMap) =>
(shape: string | number): unknown => {
const handler = pattern[shape] ?? pattern["_"];
return handler === undefined
? undefined
: Reflect.apply(handler, undefined, [shape]);
};
// oxlint-disable-next-line typescript/no-explicit-any typescript/no-unsafe-type-assertion
(pattern[shape] ?? (pattern as any)["_"])(shape);
export const strict =
<T extends string | number>(): StrictFn<T> =>
(pattern: HandlerMap) =>
dispatch(pattern);
// ============================================================================
// ❌ Exhaustive
// ❌ ReturnsStrict
// ============================================================================
export const getPrimitiveUnionMatcherPartialW: <
T extends string | number,
>() => <P extends PatternPrimitiveUnionPartial<unknown, T>>(
// `Simplify<P>` is the inference hook: callers infer `P` from the argument.
// the second half pins the impl parameter's `R` to `PatternReturns<P>`.
// that makes the `= getPrimitiveUnionMatcherPartial` assignment type-check.
// neither half works alone.
// without the witness the union's `_` arm demands `_ ∈ keyof P`.
// without `Simplify<P>` the parameter types do not compare.
pattern: Simplify<P> & PatternPrimitiveUnionPartial<PatternReturns<P>, T>,
) => UnaryFn<T, PatternReturns<P>> = getPrimitiveUnionMatcherPartial;
export const widened =
<T extends string | number>(): WidenedFn<T> =>
(pattern: HandlerMap) =>
dispatch(pattern);