⚡ Inline the tag read into dispatch
This commit is contained in:
1 parent
3f22e5ca01
commit
6f4f509b69
1 file changed
+11
-12
+11
-12
@@ -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;
|
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>;
|
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 =
|
const dispatch =
|
||||||
(k: PropertyKey) =>
|
(k: PropertyKey) =>
|
||||||
(handlers: HandlerMap, fallback?: UnaryFn<never, unknown>) =>
|
(handlers: HandlerMap, fallback?: UnaryFn<never, unknown>) =>
|
||||||
(shape: object): unknown =>
|
(shape: object): unknown => {
|
||||||
(
|
// `object` carries no index signature, so the read needs the assertion;
|
||||||
handlers[tagAt(shape, k)] ??
|
// 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 ??
|
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
|
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
||||||
shape as never,
|
shape as never,
|
||||||
);
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export const getTaggedUnionMatcher =
|
export const getTaggedUnionMatcher =
|
||||||
<T extends object>() =>
|
<T extends object>() =>
|
||||||
|
|||||||
Reference in new issue
Block a user