String(shape) defeats V8's numeric-key fast path (measured ~2x on number-keyed dispatch). JS already coerces boolean/null/undefined to the same property key, so assert shape to string | number and index directly. The assertion is TS2538-only; the facade keeps it sound. Needs a source no-unsafe-type-assertion disable, next to the existing one.
135 lines
5.4 KiB
TypeScript
135 lines
5.4 KiB
TypeScript
import type { Exact, ValueOf } from "type-fest";
|
|
|
|
type UnaryFn<T, R> = (shape: T) => R;
|
|
|
|
// The primitive universe a matcher can discriminate. `boolean` is admitted as
|
|
// the pair `true | false`; see README § Caveats for the unsupported members.
|
|
type Matchable = string | number | boolean | null | undefined;
|
|
|
|
// `boolean`, `null` and `undefined` cannot be property keys, so a mapped type
|
|
// over the universe keys each non-key member by its stringification. `Param`
|
|
// inverts that projection, so a handler callback still receives the *real*
|
|
// member (`true`, not `"true"`) — see README § Caveats for the limits.
|
|
type PatternKey<T> = T extends boolean
|
|
? T extends true
|
|
? "true"
|
|
: "false"
|
|
: T extends null
|
|
? "null"
|
|
: T extends undefined
|
|
? "undefined"
|
|
: T;
|
|
type PatternParam<K> = K extends "true"
|
|
? true
|
|
: K extends "false"
|
|
? false
|
|
: K extends "null"
|
|
? null
|
|
: K extends "undefined"
|
|
? undefined
|
|
: K;
|
|
|
|
// `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<T extends Matchable, R> = {
|
|
[K in PatternKey<T>]: UnaryFn<PatternParam<K>, R>;
|
|
};
|
|
|
|
// The fallback is a *second argument*, not a property of the handler map,
|
|
// because its parameter is the remainder `Exclude<T, keyof Handled>` and TypeScript
|
|
// fixes a property's contextual type before it infers its sibling keys. A later
|
|
// argument, by contrast, is contextually typed from inference on an earlier
|
|
// one, so the split is what makes the remainder expressible at all.
|
|
// See development/library.md.
|
|
type Fallback<T extends Matchable, Handled, R> = UnaryFn<
|
|
Exclude<T, PatternParam<keyof Handled>>,
|
|
R
|
|
>;
|
|
|
|
// A fallback is redundant once the handler map covers `T`. The guard is folded
|
|
// into `Handled`'s own (self-referential) constraint so it is checked *after*
|
|
// inference; a conditional in the fallback's parameter type is evaluated while
|
|
// `Handled` is still its constraint and would reject context-sensitive partial
|
|
// maps. That placement also fixes where the diagnostic lands: the constraint
|
|
// failure is reported on the argument that inferred `Handled` (the handler
|
|
// map), so the required property is spelled as the message instead of relying
|
|
// on its position. See development/library.md.
|
|
interface RedundantFallback {
|
|
readonly "every case is already handled, so the fallback is redundant": never;
|
|
}
|
|
type MustBePartial<T extends Matchable, Handled> =
|
|
PatternKey<T> extends keyof Handled ? RedundantFallback : unknown;
|
|
|
|
// TypeScript does not apply the excess-property check to a generic constraint,
|
|
// so `Exact` restores it for the generic forms: a handler map can otherwise
|
|
// carry keys outside `T`.
|
|
|
|
// oxlint-disable typescript/unified-signatures
|
|
// Strict returns: one common `R`. Overload order is load-bearing:
|
|
// #1 Handlers (first) -> the exhaustive form and the autocomplete popup
|
|
// #2 Fallback (last) -> accepts a partial handler map plus a fallback
|
|
interface MatcherStrict<T extends Matchable> {
|
|
<R>(handlers: Handlers<T, R>): UnaryFn<T, R>;
|
|
<
|
|
R,
|
|
Handled extends Exact<Partial<Handlers<T, R>>, Handled> &
|
|
MustBePartial<T, Handled>,
|
|
>(
|
|
handlers: Handled & Partial<Handlers<T, R>>,
|
|
fallback: Fallback<T, Handled, R>,
|
|
): UnaryFn<T, R>;
|
|
}
|
|
// oxlint-enable typescript/unified-signatures
|
|
|
|
// Widened returns: the union of every handler's return type. `P` is inferred
|
|
// from the whole handler map, whose closed constraint supplies the
|
|
// contextual/autocomplete type.
|
|
// oxlint-disable typescript/unified-signatures
|
|
interface MatcherWidening<T extends Matchable> {
|
|
<P extends Exact<Handlers<T, unknown>, P>>(
|
|
handlers: P,
|
|
): UnaryFn<T, PatternReturns<P>>;
|
|
<
|
|
R,
|
|
Handled extends Exact<Partial<Handlers<T, unknown>>, Handled> &
|
|
MustBePartial<T, Handled>,
|
|
>(
|
|
handlers: Handled,
|
|
fallback: Fallback<T, Handled, R>,
|
|
): UnaryFn<T, PatternReturns<Handled> | R>;
|
|
}
|
|
// oxlint-enable typescript/unified-signatures
|
|
|
|
type HandlerMap = Record<string | number, UnaryFn<never, unknown> | undefined>;
|
|
|
|
const dispatch =
|
|
(handlers: HandlerMap, fallback?: UnaryFn<never, unknown>) =>
|
|
(shape: Matchable): unknown =>
|
|
// `handlers[true]` already coerces to the `"true"` property at runtime,
|
|
// identical to `handlers[String(shape)]`, so indexing with `shape`
|
|
// directly is sound: `shape` is a facade-checked universe member and
|
|
// `PatternKey` only ever produces valid property keys. The assertion is
|
|
// needed solely because TypeScript forbids indexing with
|
|
// `boolean`/`null`/`undefined` (TS2538); it buys the number fast path.
|
|
(
|
|
handlers[
|
|
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
shape as string | number
|
|
] ??
|
|
fallback ??
|
|
(() => {
|
|
throw new Error(`Unhandled shape: ${String(shape)}`);
|
|
})
|
|
)(
|
|
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
shape as never,
|
|
);
|
|
|
|
export const getMatcher = <T extends Matchable>(): MatcherStrict<T> => dispatch;
|
|
export const getMatcherW = <T extends Matchable>(): MatcherWidening<T> =>
|
|
dispatch;
|