⚡ Inline the tag read into dispatch

This commit is contained in:
tmu committed 2026-09-21 23:02:56 +00:00
1 parent 3f22e5ca01
commit 6f4f509b69
1 file changed
+11 -12
+11 -12
View File
@@ -1,4 +1,4 @@
import type { Exact, ValueOf } from "type-fest";
import type { Exact, UnknownRecord, ValueOf } from "type-fest";
type UnaryFn<T, R> = (shape: T) => R;
@@ -98,27 +98,26 @@ interface TaggedUnionMatcherWidening<T extends object, K extends keyof T> {
type HandlerMap = Record<string | number, UnaryFn<never, unknown> | undefined>;
// `object` carries no index signature, so the read needs the assertion; the
// factory admits only keys whose values are `string | number` tags, so the
// result is narrowed to the map's key space.
const tagAt = (shape: object, k: PropertyKey): string | number =>
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
(shape as Record<PropertyKey, unknown>)[k] as string | number;
const dispatch =
(k: PropertyKey) =>
(handlers: HandlerMap, fallback?: UnaryFn<never, unknown>) =>
(shape: object): unknown =>
(
handlers[tagAt(shape, k)] ??
(shape: object): unknown => {
// `object` carries no index signature, so the read needs the assertion;
// the factory admits only keys whose values are `string | number` tags,
// so the result is narrowed to the map's key space.
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
const tag = (shape as UnknownRecord)[k] as string | number;
return (
handlers[tag] ??
fallback ??
(() => {
throw new Error(`Unhandled tag: ${String(tagAt(shape, k))}`);
throw new Error(`Unhandled tag: ${String(tag)}`);
})
)(
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
shape as never,
);
};
export const getTaggedUnionMatcher =
<T extends object>() =>