✨ 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:
1 parent
c32fe08c73
commit
45495fe2a8
5 files changed
+268
-17
No files matched your search
@@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
## [Unreleased]
|
||||
|
||||
- reject a fallback when the handler map already covers the universe
|
||||
- allow boolean, null and undefined in the matcher universe
|
||||
|
||||
## [0.4.0] - 2026-09-20
|
||||
|
||||
|
||||
+3
-2
@@ -52,8 +52,9 @@ Bugs:
|
||||
→ `handleExit` returns `io.EOF`, cancelling the background context while `Session.updateWatches` is still in flight; the bare error is flushed to stderr and the server exits 1
|
||||
→ close stdin after `shutdown` instead of sending `exit`; the server exits cleanly (code 0, no output), kill kept as a fallback
|
||||
Enhancements:
|
||||
☐ Allow boolean literals in primitive union patterns (e.g. `true: () => "yes"`) @medium
|
||||
☐ Are there other primitive types that should be supported in union patterns? (e.g. `bigint`, `symbol`) @medium
|
||||
✔ Allow boolean literals in primitive union patterns (e.g. `true: () => "yes"`) @medium @done
|
||||
✔ Are there other primitive types that should be supported in union patterns? (e.g. `bigint`, `symbol`) @medium @done
|
||||
→ added boolean, null and undefined; rejected `symbol` (compile-time brand, nothing at runtime) and `bigint` (not a property key)
|
||||
|
||||
Documentation:
|
||||
☐ Bring README.md back to its previous form — synopsis and examples restored, in the correct place
|
||||
|
||||
@@ -91,3 +91,36 @@ Each factory is two overloads whose order is load-bearing:
|
||||
- `Parameters<typeof factory>[0]` resolves only the **last** overload, so it is
|
||||
not a sound "rejected" oracle for a factory. Factory-negative tests use
|
||||
`@ts-expect-error` call sites (the test file only — the general ban stands).
|
||||
|
||||
## Primitive universe
|
||||
|
||||
#### Decision (2026-09)
|
||||
|
||||
The universe (`Matchable`) is `string | number | boolean | null | undefined`,
|
||||
with `boolean` admitted as `true | false`. `symbol` and `bigint` are not.
|
||||
|
||||
`boolean`/`null`/`undefined` are not property keys, so handler-map keys are a
|
||||
projection (`PatternKey`: each member stringified) and `PatternParam` inverts
|
||||
it, so callbacks receive the real member (`true`, not `"true"`). The popup
|
||||
offers `true`, `false`, `null`, `undefined` by name (verified over LSP).
|
||||
|
||||
#### Why
|
||||
|
||||
- Runtime dispatch is unchanged in effect: `handlers[true]` already coerces to
|
||||
`"true"`. `dispatch` wraps the index in `String()` only because TypeScript
|
||||
forbids indexing with `boolean`/`null`/`undefined` (`TS2538`).
|
||||
|
||||
#### Rejected
|
||||
|
||||
- **`symbol`.** A brand is a compile-time phantom — nothing to match at
|
||||
runtime; the popup cannot offer symbol keys anyway.
|
||||
- **`bigint`.** Not a valid property key; a stringified key (`"1"`) collides
|
||||
with numeric `1`.
|
||||
- **`NaN` / `-0`.** No literal type exists; they stay one `number`.
|
||||
|
||||
#### Known issue
|
||||
|
||||
- A universe mixing a member with its stringification (`1 | "1"`,
|
||||
`true | "true"`, `null | "null"`) collapses to one handler key and routes
|
||||
both members to it. Pre-existing for `1 | "1"`; now reachable for the new
|
||||
members. Not guarded at the type level.
|
||||
+184
-1
@@ -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
@@ -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;
|
||||
Reference in new issue
Block a user