import type { ValueOf } from "type-fest"; type UnaryFn = (shape: T) => R; // `Extract` drops optional handlers (`undefined`) so `PatternReturns` also works // when `P`'s constraint has optional keys. type PatternReturns

= ReturnType< Extract, (...args: never[]) => unknown> >; type Handlers = { [K in T]: UnaryFn }; // Fallback form: `_` is a required key, the T-keys are optional. type Fallback = Partial> & { _: UnaryFn; }; // Completion form: T-keys required, `_` optional. Overload #1, because // TypeScript takes the *first* overload as the contextual type for the popup. type ExhaustiveLoose = Handlers & { _?: UnaryFn; }; // oxlint-disable typescript/unified-signatures // 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 MatcherStrict { (pattern: ExhaustiveLoose): UnaryFn; (pattern: Fallback): UnaryFn; (pattern: Handlers): UnaryFn; } // oxlint-enable typescript/unified-signatures // Widened returns: the union of every handler's return type. `P` is inferred // from the whole parameter, whose closed constraint supplies the // contextual/autocomplete type; the `keyof P` guard appended to each overload // rejects keys outside `T`/`_`. interface MatcherWidening {

>( pattern: P & (keyof P extends T | "_" ? unknown : never), ): UnaryFn>;

>( pattern: P & (keyof P extends T | "_" ? unknown : never), ): UnaryFn>;

>( pattern: P & (keyof P extends T | "_" ? unknown : never), ): UnaryFn>; } type HandlerMap = Record | undefined>; const dispatch = (pattern: HandlerMap) => (shape: string | number): unknown => // oxlint-disable-next-line typescript/no-non-null-assertion typescript/no-unsafe-type-assertion (pattern[shape] ?? pattern["_"]!)(shape as never); export const getMatcher = (): MatcherStrict => dispatch; export const getMatcherW = (): MatcherWidening => dispatch;