✨ Match boolean, null and undefined

Extend the matcher universe beyond string | number so a union can carry
boolean, null and undefined members. true|false, null and undefined are
not property keys, so handler keys are their stringification while the
callback still receives the real member. Symbols are rejected (a brand
is compile-time only) and bigint is not a property key.
This commit is contained in:
tmu committed 2026-09-21 09:44:44 +00:00
1 parent c32fe08c73
commit 45495fe2a8
5 files changed
+268 -17

No files matched your search

+184 -1
View File
@@ -95,6 +95,50 @@ test("getMatcher: dispatches on mixed string and numeric keys", () => {
assert.equal(matcher(2), 20);
});
test("getMatcher: dispatches on boolean literals", () => {
// Arrange
const factory = getMatcher<boolean>();
// Act
const matcher = factory({
true: (s) => {
expectTypeOf(s).toEqualTypeOf<true>();
return 1;
},
false: (s) => {
expectTypeOf(s).toEqualTypeOf<false>();
return 2;
},
});
// Assert
expectTypeOf(matcher).toEqualTypeOf<(shape: boolean) => number>();
assert.equal(matcher(true), 1);
assert.equal(matcher(false), 2);
});
test("getMatcher: dispatches on null and undefined", () => {
// Arrange
const factory = getMatcher<null | undefined>();
// Act
const matcher = factory({
null: (s) => {
expectTypeOf(s).toEqualTypeOf<null>();
return "null";
},
undefined: (s) => {
expectTypeOf(s).toEqualTypeOf<undefined>();
return "undefined";
},
});
// Assert
expectTypeOf(matcher).toEqualTypeOf<(shape: null | undefined) => string>();
assert.equal(matcher(null), "null");
assert.equal(matcher(undefined), "undefined");
});
// ============================================================================
// API: getMatcher — ❌ Exhaustive (fallback) / ✔️ ReturnsStrict
// ============================================================================
@@ -157,6 +201,41 @@ test("getMatcher: a `_` fallback routes mixed string and numeric gaps", () => {
assert.equal(matcher(2), "fallback");
});
test("getMatcher: a `_` fallback receives unhandled boolean and nullish keys", () => {
// Arrange
const factory = getMatcher<"a" | true | false | null | undefined>();
// Act
const matcher = factory(
{
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
return 1 as const;
},
null: (s) => {
expectTypeOf(s).toEqualTypeOf<null>();
return 2 as const;
},
},
(s) => {
// `true` and `false` are keyed as `"true"`/`"false"` but the
// fallback still sees them as booleans.
expectTypeOf(s).toEqualTypeOf<true | false | undefined>();
return 3 as const;
},
);
// Assert
expectTypeOf(matcher).toEqualTypeOf<
(shape: "a" | true | false | null | undefined) => 1 | 2 | 3
>();
assert.equal(matcher("a"), 1);
assert.equal(matcher(true), 3);
assert.equal(matcher(false), 3);
assert.equal(matcher(null), 2);
assert.equal(matcher(undefined), 3);
});
// ============================================================================
// API: getMatcherW — ✔️ Exhaustive / ❌ ReturnsStrict
// ============================================================================
@@ -220,6 +299,40 @@ test("getMatcherW: dispatches on mixed string and numeric keys", () => {
assert.equal(matcher(2), 20);
});
test("getMatcherW: exhaustive boolean and nullish widen to the union", () => {
// Arrange
const factory = getMatcherW<boolean | null | undefined>();
// Act
const matcher = factory({
true: (s) => {
expectTypeOf(s).toEqualTypeOf<true>();
return "yes" as const;
},
false: (s) => {
expectTypeOf(s).toEqualTypeOf<false>();
return "no" as const;
},
null: (s) => {
expectTypeOf(s).toEqualTypeOf<null>();
return 0 as const;
},
undefined: (s) => {
expectTypeOf(s).toEqualTypeOf<undefined>();
return 1 as const;
},
});
// Assert
expectTypeOf(matcher).toEqualTypeOf<
(shape: boolean | null | undefined) => "yes" | "no" | 0 | 1
>();
assert.equal(matcher(true), "yes");
assert.equal(matcher(false), "no");
assert.equal(matcher(null), 0);
assert.equal(matcher(undefined), 1);
});
// ============================================================================
// API: getMatcherW — ❌ Exhaustive (fallback) / ❌ ReturnsStrict
// ============================================================================
@@ -313,6 +426,27 @@ test("getMatcher factory rejects patterns outside its contract", () => {
factory({ a: () => 1, b: () => 2 }, () => 0);
});
test("getMatcher factory rejects non-exhaustive boolean and nullish maps", () => {
// Arrange
const factory = getMatcher<boolean | null | undefined>();
// Act / Assert — the calls below must not compile
// @ts-expect-error only `true` is handled; `false`, `null`, `undefined` are not
factory({ true: () => 1 });
// @ts-expect-error `null` and `undefined` are not handled
factory({ true: () => 1, false: () => 2 });
factory(
// @ts-expect-error a fallback is redundant once the map covers the universe
{
true: () => 1,
false: () => 2,
null: () => 3,
undefined: () => 4,
},
() => 0,
);
});
test("getMatcher: an open universe keeps the fallback's remainder open", () => {
// Arrange
const factory = getMatcher<string>();
@@ -363,6 +497,17 @@ test("getMatcher: an unhandled shape throws without a fallback", () => {
assert.throws(() => matcher("b"), /Unhandled shape: b/);
});
test("getMatcher: an unhandled boolean shape throws without a fallback", () => {
// Arrange — an `string | boolean` universe widens its handler map to an
// index signature, so the runtime map's exhaustiveness is not provable.
const handlers: Record<string, () => number> = { true: () => 1 };
const matcher = getMatcher<string | boolean>()(handlers);
// Act / Assert
assert.equal(matcher(true), 1);
assert.throws(() => matcher(false), /Unhandled shape: false/);
});
// ============================================================================
// Autocomplete — the language server is the oracle, not the type system
// ============================================================================
@@ -381,6 +526,7 @@ interface LabelsProbe {
readonly name: string;
readonly factory: "getMatcher" | "getMatcherW";
readonly body: string;
readonly universe?: string;
readonly tail?: string;
}
@@ -388,6 +534,7 @@ const labelsFor = ({
name,
factory,
body,
universe = UNIVERSE,
tail = "",
}: LabelsProbe): Promise<readonly string[]> => {
const session = new LspSession(REPO_ROOT);
@@ -395,7 +542,7 @@ const labelsFor = ({
file: `src/__autocomplete_${name}.ts`,
source: [
`import { ${factory} } from "./index.ts";`,
`const m = ${factory}<${UNIVERSE}>()({`,
`const m = ${factory}<${universe}>()({`,
body,
`}${tail});`,
"",
@@ -511,3 +658,39 @@ test("autocomplete: `getMatcherW` also offers optional keys with a fallback", ()
assert.deepEqual([...result], ["a?", "b?", "c?"]);
});
});
test("autocomplete: boolean and nullish keys are offered by name", () => {
// Arrange
const name = "getMatcher_boolean_nullish";
// Act
const labels = labelsFor({
name,
factory: "getMatcher",
universe: "boolean | null | undefined",
body: " /*COMPLETE*/",
});
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["false", "null", "true", "undefined"]);
});
});
test("autocomplete: a handled boolean literal drops out of the popup", () => {
// Arrange
const name = "getMatcher_boolean_after_key";
// Act
const labels = labelsFor({
name,
factory: "getMatcher",
universe: "boolean | null | undefined",
body: " true: () => 1,\n /*COMPLETE*/",
});
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["false", "null", "undefined"]);
});
});
+47 -14
View File
@@ -2,13 +2,45 @@ 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`; `symbol` is deliberately absent (a brand is a
// compile-time phantom, so there is nothing to match at runtime).
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"`). A universe mixing a member with the string it
// stringifies to (e.g. `true | "true"`) collapses to one key and is not
// representable — see development/library.md.
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 string | number, R> = { [K in T]: UnaryFn<K, R> };
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
@@ -16,8 +48,8 @@ type Handlers<T extends string | number, R> = { [K in T]: UnaryFn<K, R> };
// 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 string | number, Handled, R> = UnaryFn<
Exclude<T, keyof Handled>,
type Fallback<T extends Matchable, Handled, R> = UnaryFn<
Exclude<T, PatternParam<keyof Handled>>,
R
>;
@@ -32,9 +64,8 @@ type Fallback<T extends string | number, Handled, R> = UnaryFn<
interface RedundantFallback {
readonly "every case is already handled, so the fallback is redundant": never;
}
type MustBePartial<T extends string | number, Handled> = T extends keyof Handled
? RedundantFallback
: unknown;
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
@@ -44,7 +75,7 @@ type MustBePartial<T extends string | number, Handled> = T extends keyof Handled
// 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 string | number> {
interface MatcherStrict<T extends Matchable> {
<R>(handlers: Handlers<T, R>): UnaryFn<T, R>;
<
R,
@@ -61,7 +92,7 @@ interface MatcherStrict<T extends string | number> {
// from the whole handler map, whose closed constraint supplies the
// contextual/autocomplete type.
// oxlint-disable typescript/unified-signatures
interface MatcherWidening<T extends string | number> {
interface MatcherWidening<T extends Matchable> {
<P extends Exact<Handlers<T, unknown>, P>>(
handlers: P,
): UnaryFn<T, PatternReturns<P>>;
@@ -80,19 +111,21 @@ type HandlerMap = Record<string | number, UnaryFn<never, unknown> | undefined>;
const dispatch =
(handlers: HandlerMap, fallback?: UnaryFn<never, unknown>) =>
(shape: string | number): unknown =>
(shape: Matchable): unknown =>
// `handlers[true]` already coerces to the `"true"` property at
// runtime; `String` is here only because TypeScript forbids
// indexing with `boolean`/`null`/`undefined` (TS2538).
(
handlers[shape] ??
handlers[String(shape)] ??
fallback ??
(() => {
throw new Error(`Unhandled shape: ${shape}`);
throw new Error(`Unhandled shape: ${String(shape)}`);
})
)(
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
shape as never,
);
export const getMatcher = <T extends string | number>(): MatcherStrict<T> =>
dispatch;
export const getMatcherW = <T extends string | number>(): MatcherWidening<T> =>
export const getMatcher = <T extends Matchable>(): MatcherStrict<T> => dispatch;
export const getMatcherW = <T extends Matchable>(): MatcherWidening<T> =>
dispatch;