Files
tiny-pattern-ts/src/primitive-union.test.ts
T
tmu 3b5269f9e1 🐛 Gate the universe to finite, literal keys
An open universe (`string`, `number`, a template literal) makes the
handler map index-like, so a partial object satisfied the exhaustive
overload and the runtime `dispatch` throw was reachable. A universe
containing a member and its stringification (`"true" | true`, `1 | "1"`)
collapsed two members onto one key.

- reject broad universes and value/stringification collisions at the
  factory, with a diagnostic naming the reason
- invert `PatternKey` against the universe (`Member<T, K>`) instead of
  `PatternParam<K>`, so a standalone `"true"` is typed `"true"`
- intersect `UniverseGate<T>` into the handler and fallback parameters,
  preserving `R` inference and the popup
2026-09-23 13:41:57 +00:00

1121 lines
35 KiB
TypeScript

import { strict as assert } from "node:assert";
import path from "node:path";
import { test } from "node:test";
import { expectTypeOf } from "expect-type";
import {
type CompletionTarget,
LspSession,
} from "#test-utils/lsp-completion.ts";
import {
getPrimitiveUnionMatcher,
getPrimitiveUnionMatcherW,
} from "./primitive-union.ts";
// ============================================================================
// API: getPrimitiveUnionMatcher — ✔️ Exhaustive / ✔️ ReturnsStrict
// ============================================================================
test("getPrimitiveUnionMatcher: exhaustive pattern infers one common return type", () => {
// Arrange
const factory = getPrimitiveUnionMatcher<"a" | "b">();
// Act
const matcher = factory({
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
assert.equal(s, "a");
return 1;
},
b: (s) => {
expectTypeOf(s).toEqualTypeOf<"b">();
assert.equal(s, "b");
return 2;
},
});
// Assert
// ✔️ ReturnsStrict: R is the best common return type, not a widening union.
expectTypeOf(matcher).toEqualTypeOf<(shape: "a" | "b") => number>();
// ❌ a value outside T must not be accepted by the matcher
expectTypeOf<"c">().not.toExtend<Parameters<typeof matcher>[0]>();
assert.equal(matcher("a"), 1);
assert.equal(matcher("b"), 2);
});
test("getPrimitiveUnionMatcher: dispatches on numeric literal keys", () => {
// Arrange
const factory = getPrimitiveUnionMatcher<1 | 2>();
// Act
const matcher = factory({
1: (n) => {
expectTypeOf(n).toEqualTypeOf<1>();
// A numeric key must not reach its handler as the string `"1"`.
assert.equal(n, 1);
return n + 1;
},
2: (n) => {
expectTypeOf(n).toEqualTypeOf<2>();
assert.equal(n, 2);
return n * 10;
},
});
// Assert
expectTypeOf(matcher).toEqualTypeOf<(shape: 1 | 2) => number>();
assert.equal(matcher(1), 2);
assert.equal(matcher(2), 20);
});
test("getPrimitiveUnionMatcher: dispatches on mixed string and numeric keys", () => {
// Arrange
const factory = getPrimitiveUnionMatcher<"a" | "b" | 1 | 2>();
// Act
const matcher = factory({
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
assert.equal(s, "a");
return 1;
},
b: (s) => {
expectTypeOf(s).toEqualTypeOf<"b">();
assert.equal(s, "b");
return 2;
},
1: (n) => {
expectTypeOf(n).toEqualTypeOf<1>();
assert.equal(n, 1);
return 10;
},
2: (n) => {
expectTypeOf(n).toEqualTypeOf<2>();
assert.equal(n, 2);
return 20;
},
});
// Assert
expectTypeOf(matcher).toEqualTypeOf<(shape: "a" | "b" | 1 | 2) => number>();
assert.equal(matcher("a"), 1);
assert.equal(matcher("b"), 2);
assert.equal(matcher(1), 10);
assert.equal(matcher(2), 20);
});
test("getPrimitiveUnionMatcher: dispatches on boolean literals", () => {
// Arrange
const factory = getPrimitiveUnionMatcher<boolean>();
// Act
const matcher = factory({
true: (s) => {
expectTypeOf(s).toEqualTypeOf<true>();
// The `true` key is a property name; the handler must still be
// called with the boolean `true`, not the string `"true"`.
assert.equal(s, true);
return 1;
},
false: (s) => {
expectTypeOf(s).toEqualTypeOf<false>();
assert.equal(s, false);
return 2;
},
});
// Assert
expectTypeOf(matcher).toEqualTypeOf<(shape: boolean) => number>();
assert.equal(matcher(true), 1);
assert.equal(matcher(false), 2);
});
test("getPrimitiveUnionMatcher: dispatches on null and undefined", () => {
// Arrange
const factory = getPrimitiveUnionMatcher<null | undefined>();
// Act
const matcher = factory({
null: (s) => {
expectTypeOf(s).toEqualTypeOf<null>();
assert.equal(s, null);
return "null";
},
undefined: (s) => {
expectTypeOf(s).toEqualTypeOf<undefined>();
assert.equal(s, undefined);
return "undefined";
},
});
// Assert
expectTypeOf(matcher).toEqualTypeOf<(shape: null | undefined) => string>();
assert.equal(matcher(null), "null");
assert.equal(matcher(undefined), "undefined");
});
// ============================================================================
// API: getPrimitiveUnionMatcher — ❌ Exhaustive (fallback) / ✔️ ReturnsStrict
// ============================================================================
test("getPrimitiveUnionMatcher: a `_` fallback receives the unhandled keys", () => {
// Arrange
const factory = getPrimitiveUnionMatcher<"a" | "b" | "c">();
// Act
const matcher = factory(
{
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
assert.equal(s, "a");
return 1 as const;
},
},
(s) => {
// The fallback sees only the keys `a` did not handle.
expectTypeOf(s).toEqualTypeOf<"b" | "c">();
assert.ok(s === "b" || s === "c");
return 2 as const;
},
);
// Assert
expectTypeOf(matcher).toEqualTypeOf<(shape: "a" | "b" | "c") => 1 | 2>();
// ❌ a value outside T must not be accepted by the matcher
expectTypeOf<"d">().not.toExtend<Parameters<typeof matcher>[0]>();
assert.equal(matcher("a"), 1);
assert.equal(matcher("b"), 2);
assert.equal(matcher("c"), 2);
});
test("getPrimitiveUnionMatcher: a `_` fallback routes mixed string and numeric gaps", () => {
// Arrange
const factory = getPrimitiveUnionMatcher<"a" | "b" | 1 | 2>();
// Act
const matcher = factory(
{
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
assert.equal(s, "a");
return "A";
},
1: (n) => {
expectTypeOf(n).toEqualTypeOf<1>();
assert.equal(n, 1);
return "one";
},
},
(s) => {
expectTypeOf(s).toEqualTypeOf<"b" | 2>();
// The gap mixes a string and a number, so the number must reach the
// fallback as `2`, never as its key text `"2"`.
assert.ok(s === "b" || s === 2);
return "fallback";
},
);
// Assert
expectTypeOf(matcher).toEqualTypeOf<(shape: "a" | "b" | 1 | 2) => string>();
assert.equal(matcher("a"), "A");
assert.equal(matcher("b"), "fallback");
assert.equal(matcher(1), "one");
assert.equal(matcher(2), "fallback");
});
test("getPrimitiveUnionMatcher: a `_` fallback receives unhandled boolean and nullish keys", () => {
// Arrange
const factory = getPrimitiveUnionMatcher<
"a" | true | false | null | undefined
>();
// Act
const matcher = factory(
{
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
assert.equal(s, "a");
return 1 as const;
},
null: (s) => {
expectTypeOf(s).toEqualTypeOf<null>();
assert.equal(s, 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>();
assert.ok(s === true || s === false || s === 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: getPrimitiveUnionMatcherW — ✔️ Exhaustive / ❌ ReturnsStrict
// ============================================================================
test("getPrimitiveUnionMatcherW: exhaustive pattern widens to the union of handler returns", () => {
// Arrange
const factory = getPrimitiveUnionMatcherW<"x" | "y">();
// Act
const matcher = factory({
x: (s) => {
expectTypeOf(s).toEqualTypeOf<"x">();
assert.equal(s, "x");
return 1 as const;
},
y: (s) => {
expectTypeOf(s).toEqualTypeOf<"y">();
assert.equal(s, "y");
return "two" as const;
},
});
// Assert
// ❌ ReturnsStrict: mixed handler returns widen to their union.
expectTypeOf(matcher).toEqualTypeOf<(shape: "x" | "y") => 1 | "two">();
// ❌ a value outside T must not be accepted by the matcher
expectTypeOf<"z">().not.toExtend<Parameters<typeof matcher>[0]>();
assert.equal(matcher("x"), 1);
assert.equal(matcher("y"), "two");
});
test("getPrimitiveUnionMatcherW: dispatches on mixed string and numeric keys", () => {
// Arrange
const factory = getPrimitiveUnionMatcherW<"a" | "b" | 1 | 2>();
// Act
const matcher = factory({
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
assert.equal(s, "a");
return "A" as const;
},
b: (s) => {
expectTypeOf(s).toEqualTypeOf<"b">();
assert.equal(s, "b");
return "B" as const;
},
1: (n) => {
expectTypeOf(n).toEqualTypeOf<1>();
assert.equal(n, 1);
return 10 as const;
},
2: (n) => {
expectTypeOf(n).toEqualTypeOf<2>();
assert.equal(n, 2);
return 20 as const;
},
});
// Assert
expectTypeOf(matcher).toEqualTypeOf<
(shape: "a" | "b" | 1 | 2) => "A" | "B" | 10 | 20
>();
assert.equal(matcher("a"), "A");
assert.equal(matcher("b"), "B");
assert.equal(matcher(1), 10);
assert.equal(matcher(2), 20);
});
test("getPrimitiveUnionMatcherW: exhaustive boolean and nullish widen to the union", () => {
// Arrange
const factory = getPrimitiveUnionMatcherW<boolean | null | undefined>();
// Act
const matcher = factory({
true: (s) => {
expectTypeOf(s).toEqualTypeOf<true>();
assert.equal(s, true);
return "yes" as const;
},
false: (s) => {
expectTypeOf(s).toEqualTypeOf<false>();
assert.equal(s, false);
return "no" as const;
},
null: (s) => {
expectTypeOf(s).toEqualTypeOf<null>();
assert.equal(s, null);
return 0 as const;
},
undefined: (s) => {
expectTypeOf(s).toEqualTypeOf<undefined>();
assert.equal(s, 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: getPrimitiveUnionMatcherW — ❌ Exhaustive (fallback) / ❌ ReturnsStrict
// ============================================================================
test("getPrimitiveUnionMatcherW: a `_` fallback widens gaps into the union", () => {
// Arrange
const factory = getPrimitiveUnionMatcherW<"x" | "y" | "z">();
// Act
const matcher = factory(
{
x: (s) => {
expectTypeOf(s).toEqualTypeOf<"x">();
assert.equal(s, "x");
return 1 as const;
},
},
(s) => {
// The fallback sees only the keys `x` did not handle.
expectTypeOf(s).toEqualTypeOf<"y" | "z">();
// Returning the shape verbatim lets the `Assert` block check the
// exact value dispatch passed.
return s;
},
);
// Assert
expectTypeOf(matcher).toEqualTypeOf<
(shape: "x" | "y" | "z") => 1 | "y" | "z"
>();
// ❌ a value outside T must not be accepted by the matcher
expectTypeOf<"w">().not.toExtend<Parameters<typeof matcher>[0]>();
assert.equal(matcher("x"), 1);
assert.equal(matcher("y"), "y");
assert.equal(matcher("z"), "z");
});
test("getPrimitiveUnionMatcherW: a `_` fallback widens mixed string and numeric returns", () => {
// Arrange
const factory = getPrimitiveUnionMatcherW<"a" | "b" | 1 | 2>();
// Act
const matcher = factory(
{
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
assert.equal(s, "a");
return "A" as const;
},
1: (n) => {
expectTypeOf(n).toEqualTypeOf<1>();
assert.equal(n, 1);
return 10 as const;
},
},
(s) => {
expectTypeOf(s).toEqualTypeOf<"b" | 2>();
// The number must arrive as `2`, not as its key text `"2"`.
assert.ok(s === "b" || s === 2);
// Returning the shape verbatim lets the `Assert` block check the
// exact value dispatch passed.
return s;
},
);
// Assert
// ❌ ReturnsStrict: mixed handler returns widen to their union.
expectTypeOf(matcher).toEqualTypeOf<
(shape: "a" | "b" | 1 | 2) => "A" | 10 | "b" | 2
>();
assert.equal(matcher("a"), "A");
assert.equal(matcher("b"), "b");
assert.equal(matcher(1), 10);
assert.equal(matcher(2), 2);
});
// ============================================================================
// Factory contracts — calls that must not compile
// ============================================================================
test("getPrimitiveUnionMatcher factory rejects patterns outside its contract", () => {
// Arrange
const factory = getPrimitiveUnionMatcher<"a" | "b">();
// Act / Assert — the calls below must not compile.
// `Parameters<typeof factory>[0]` resolves only the *last* overload, so it
// is not a sound "rejected" oracle (an accepted partial pattern does not
// extend it either); the call sites are the oracle instead.
factory({
a: () => 1,
b: () => 2,
// @ts-expect-error `c` is not part of the universe `"a" | "b"`
c: () => 3,
});
// @ts-expect-error a gap without a `_` fallback is not exhaustive
factory({ a: () => 1 });
// @ts-expect-error a `string` fallback does not fit the `number` handler
factory({ a: () => 1 }, () => "x");
// @ts-expect-error a fallback is redundant once the map covers the universe
factory({ a: () => 1, b: () => 2 }, () => 0);
});
test("getPrimitiveUnionMatcher factory rejects non-exhaustive boolean and nullish maps", () => {
// Arrange
const factory = getPrimitiveUnionMatcher<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("getPrimitiveUnionMatcher: a standalone stringified literal is typed by the member, not its key", () => {
// `"true"` is a string member whose `PatternKey` is `"true"`; inverting the
// key must recover the string, not the boolean that also stringifies to it.
// Arrange
const factory = getPrimitiveUnionMatcher<"true" | "1">();
// Act
const matcher = factory({
true: (s) => {
expectTypeOf(s).toEqualTypeOf<"true">();
assert.equal(s, "true");
return 1;
},
"1": (s) => {
expectTypeOf(s).toEqualTypeOf<"1">();
assert.equal(s, "1");
return 2;
},
});
// Assert
assert.equal(matcher("true"), 1);
assert.equal(matcher("1"), 2);
});
test("getPrimitiveUnionMatcher: a broad universe is rejected", () => {
// Act / Assert — the calls below must not compile
// @ts-expect-error `string` is not a finite union of literals
getPrimitiveUnionMatcher<string>()({ a: () => 1 });
// @ts-expect-error `number` is not a finite union of literals
getPrimitiveUnionMatcher<number>()({ 1: () => 1 });
// @ts-expect-error a template literal is open
getPrimitiveUnionMatcher<`a${string}`>()({ a: () => 1 });
// @ts-expect-error `string | boolean` is open because of `string`
getPrimitiveUnionMatcher<string | boolean>()({ true: () => 1 });
// @ts-expect-error the widening factory rejects broad universes too
getPrimitiveUnionMatcherW<string>()({ a: () => 1 });
});
test("getPrimitiveUnionMatcher: a value/stringification collision is rejected", () => {
// Act / Assert — the calls below must not compile
// @ts-expect-error `true` collides with the string `"true"`
getPrimitiveUnionMatcher<"true" | true>()({ true: () => 1 });
// @ts-expect-error `false` collides with the string `"false"`
getPrimitiveUnionMatcher<"false" | false>()({ false: () => 1 });
// @ts-expect-error `null` collides with the string `"null"`
getPrimitiveUnionMatcher<"null" | null>()({ null: () => 1 });
// @ts-expect-error `undefined` collides with the string `"undefined"`
getPrimitiveUnionMatcher<"undefined" | undefined>()({
undefined: () => 1,
});
// @ts-expect-error the number `1` collides with the string `"1"`
getPrimitiveUnionMatcher<1 | "1">()({ 1: () => 1 });
});
test("getPrimitiveUnionMatcher: a collision is rejected beside legal members", () => {
// Act / Assert — the calls below must not compile; the legal members do not
// mask the collision. Each map is otherwise complete, so only the collision
// can make it invalid.
// @ts-expect-error `true` collides with `"true"` beside legal members
getPrimitiveUnionMatcher<"true" | true | "a" | 2>()({
true: () => 1,
a: () => 2,
2: () => 3,
});
// @ts-expect-error `false` collides with `"false"` beside legal members
getPrimitiveUnionMatcher<"false" | false | "a" | 2>()({
false: () => 1,
a: () => 2,
2: () => 3,
});
// @ts-expect-error `null` collides with `"null"` beside legal members
getPrimitiveUnionMatcher<"null" | null | "a" | 2>()({
null: () => 1,
a: () => 2,
2: () => 3,
});
// @ts-expect-error `undefined` collides with `"undefined"` beside legal members
getPrimitiveUnionMatcher<"undefined" | undefined | "a" | 2>()({
undefined: () => 1,
a: () => 2,
2: () => 3,
});
// @ts-expect-error `1` collides with `"1"` beside legal members
getPrimitiveUnionMatcher<1 | "1" | "a" | true>()({
1: () => 1,
a: () => 2,
true: () => 3,
});
});
test('getPrimitiveUnionMatcher: `"true"` and a bare `false` are legal together', () => {
// Arrange — `false` stringifies to `"false"`, so it does not collide with
// the string member `"true"`.
const factory = getPrimitiveUnionMatcher<"true" | false | "a" | 2>();
// Act
const matcher = factory({
true: (s) => {
expectTypeOf(s).toEqualTypeOf<"true">();
assert.equal(s, "true");
return 1;
},
false: (s) => {
expectTypeOf(s).toEqualTypeOf<false>();
assert.equal(s, false);
return 2;
},
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
assert.equal(s, "a");
return 3;
},
2: (s) => {
expectTypeOf(s).toEqualTypeOf<2>();
assert.equal(s, 2);
return 4;
},
});
// Assert
assert.equal(matcher("true"), 1);
assert.equal(matcher(false), 2);
assert.equal(matcher("a"), 3);
assert.equal(matcher(2), 4);
});
test('getPrimitiveUnionMatcher: `"false"` and a bare `true` are legal together', () => {
// Arrange — `true` stringifies to `"true"`, not `"false"`.
const factory = getPrimitiveUnionMatcher<"false" | true | "a" | 2>();
// Act
const matcher = factory({
false: (s) => {
expectTypeOf(s).toEqualTypeOf<"false">();
assert.equal(s, "false");
return 1;
},
true: (s) => {
expectTypeOf(s).toEqualTypeOf<true>();
assert.equal(s, true);
return 2;
},
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
assert.equal(s, "a");
return 3;
},
2: (s) => {
expectTypeOf(s).toEqualTypeOf<2>();
assert.equal(s, 2);
return 4;
},
});
// Assert
assert.equal(matcher("false"), 1);
assert.equal(matcher(true), 2);
assert.equal(matcher("a"), 3);
assert.equal(matcher(2), 4);
});
test('getPrimitiveUnionMatcher: `"null"` and a bare `undefined` are legal together', () => {
// Arrange — `undefined` stringifies to `"undefined"`, not `"null"`.
const factory = getPrimitiveUnionMatcher<"null" | undefined | "a" | 2>();
// Act
const matcher = factory({
null: (s) => {
expectTypeOf(s).toEqualTypeOf<"null">();
assert.equal(s, "null");
return 1;
},
undefined: (s) => {
expectTypeOf(s).toEqualTypeOf<undefined>();
assert.equal(s, undefined);
return 2;
},
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
assert.equal(s, "a");
return 3;
},
2: (s) => {
expectTypeOf(s).toEqualTypeOf<2>();
assert.equal(s, 2);
return 4;
},
});
// Assert
assert.equal(matcher("null"), 1);
assert.equal(matcher(undefined), 2);
assert.equal(matcher("a"), 3);
assert.equal(matcher(2), 4);
});
test('getPrimitiveUnionMatcher: `"undefined"` and a bare `null` are legal together', () => {
// Arrange — `null` stringifies to `"null"`, not `"undefined"`.
const factory = getPrimitiveUnionMatcher<"undefined" | null | "a" | 2>();
// Act
const matcher = factory({
undefined: (s) => {
expectTypeOf(s).toEqualTypeOf<"undefined">();
assert.equal(s, "undefined");
return 1;
},
null: (s) => {
expectTypeOf(s).toEqualTypeOf<null>();
assert.equal(s, null);
return 2;
},
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
assert.equal(s, "a");
return 3;
},
2: (s) => {
expectTypeOf(s).toEqualTypeOf<2>();
assert.equal(s, 2);
return 4;
},
});
// Assert
assert.equal(matcher("undefined"), 1);
assert.equal(matcher(null), 2);
assert.equal(matcher("a"), 3);
assert.equal(matcher(2), 4);
});
test('getPrimitiveUnionMatcher: `"1"` beside other numbers and strings is legal', () => {
// Arrange — the task's example: `"1"` is the string member, `2` and `3`
// are bare numbers, `"4"` is another string. No stringification lands on
// another member.
const factory = getPrimitiveUnionMatcher<"1" | 2 | 3 | "4">();
// Act
const matcher = factory({
"1": (s) => {
expectTypeOf(s).toEqualTypeOf<"1">();
assert.equal(s, "1");
return 1;
},
2: (s) => {
expectTypeOf(s).toEqualTypeOf<2>();
assert.equal(s, 2);
return 2;
},
3: (s) => {
expectTypeOf(s).toEqualTypeOf<3>();
assert.equal(s, 3);
return 3;
},
"4": (s) => {
expectTypeOf(s).toEqualTypeOf<"4">();
assert.equal(s, "4");
return 4;
},
});
// Assert
assert.equal(matcher("1"), 1);
assert.equal(matcher(2), 2);
assert.equal(matcher(3), 3);
assert.equal(matcher("4"), 4);
});
// The maximum legal universe needs one handler per member; the statement count
// is inherent to the case.
// oxlint-disable-next-line max-statements
test("getPrimitiveUnionMatcher: the maximum legal universe is supported", () => {
// Arrange — every Matchable kind, one representation per value, plus extra
// literals. No member's stringification is another member.
type Legal =
| "true"
| false
| null
| undefined
| "1"
| 2
| 3
| "a"
| "b"
| "4";
const factory = getPrimitiveUnionMatcher<Legal>();
// Act
const matcher = factory({
true: (s) => {
expectTypeOf(s).toEqualTypeOf<"true">();
assert.equal(s, "true");
return 1;
},
false: (s) => {
expectTypeOf(s).toEqualTypeOf<false>();
assert.equal(s, false);
return 2;
},
null: (s) => {
expectTypeOf(s).toEqualTypeOf<null>();
assert.equal(s, null);
return 3;
},
undefined: (s) => {
expectTypeOf(s).toEqualTypeOf<undefined>();
assert.equal(s, undefined);
return 4;
},
"1": (s) => {
expectTypeOf(s).toEqualTypeOf<"1">();
assert.equal(s, "1");
return 5;
},
2: (s) => {
expectTypeOf(s).toEqualTypeOf<2>();
assert.equal(s, 2);
return 6;
},
3: (s) => {
expectTypeOf(s).toEqualTypeOf<3>();
assert.equal(s, 3);
return 7;
},
a: (s) => {
expectTypeOf(s).toEqualTypeOf<"a">();
assert.equal(s, "a");
return 8;
},
b: (s) => {
expectTypeOf(s).toEqualTypeOf<"b">();
assert.equal(s, "b");
return 9;
},
"4": (s) => {
expectTypeOf(s).toEqualTypeOf<"4">();
assert.equal(s, "4");
return 10;
},
});
// Assert
expectTypeOf(matcher).toEqualTypeOf<(shape: Legal) => number>();
assert.equal(matcher("true"), 1);
assert.equal(matcher(false), 2);
assert.equal(matcher(null), 3);
assert.equal(matcher(undefined), 4);
assert.equal(matcher("1"), 5);
assert.equal(matcher(2), 6);
assert.equal(matcher(3), 7);
assert.equal(matcher("a"), 8);
assert.equal(matcher("b"), 9);
assert.equal(matcher("4"), 10);
});
test("getPrimitiveUnionMatcher: the maximum illegal universe is rejected", () => {
// Arrange — every value paired with its stringification.
type Illegal =
| "true"
| true
| "false"
| false
| "null"
| null
| "undefined"
| undefined
| "1"
| 1;
// Act / Assert — the call below must not compile
// @ts-expect-error every value collides with its stringification
getPrimitiveUnionMatcher<Illegal>()({
true: () => 1,
false: () => 2,
null: () => 3,
undefined: () => 4,
"1": () => 5,
});
});
test("getPrimitiveUnionMatcher: an open universe is rejected with a fallback too", () => {
// Act / Assert — the call below must not compile; a broad universe is
// unsupported whether or not a fallback is supplied.
// @ts-expect-error `string` is not a finite union of literals
getPrimitiveUnionMatcher<string>()({ a: () => 1 }, () => 2);
});
test("getPrimitiveUnionMatcherW factory rejects patterns outside its contract", () => {
// Arrange
const factory = getPrimitiveUnionMatcherW<"x" | "y">();
// Act / Assert — the calls below must not compile
factory({
x: () => 1 as const,
y: () => 2 as const,
// @ts-expect-error `z` is not part of the universe `"x" | "y"`
z: () => 3 as const,
});
// @ts-expect-error a gap without a `_` fallback is not exhaustive
factory({ x: () => 1 as const });
// @ts-expect-error a fallback is redundant once the map covers the universe
factory({ x: () => 1 as const, y: () => 2 as const }, () => 0);
});
// ============================================================================
// Dispatch — runtime behavior
// ============================================================================
test("getPrimitiveUnionMatcher: an unhandled shape throws without a fallback", () => {
// Arrange — a finite universe is exhaustive through the typed API, so the
// defensive throw is reachable only by widening the factory and dropping a
// handler.
const bypass: Function = getPrimitiveUnionMatcher<"a" | "b">();
const matcher: (shape: "a" | "b") => number = bypass({ a: () => 1 });
// Act / Assert
assert.equal(matcher("a"), 1);
assert.throws(() => matcher("b"), /Unhandled shape: b/);
});
test("getPrimitiveUnionMatcher: an unhandled boolean shape throws without a fallback", () => {
// Arrange — as above; `true` indexes the map as the property `"true"`, but
// the handler is still called with the boolean.
const bypass: Function = getPrimitiveUnionMatcher<true | false>();
const matcher: (shape: boolean) => number = bypass({
true: (shape: boolean) => {
assert.equal(shape, true);
return 1;
},
});
// 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
// ============================================================================
// Completion is a contextual-type property that the type system cannot observe,
// so the cases below read the popup from the repo's language server (via the
// test helper) rather than pairing `expectTypeOf` with `assert` — see
// development/testing.md § Autocomplete. They probe the *matcher's* overloads,
// which is why they live with the matcher and not with the helper.
const REPO_ROOT = path.resolve(import.meta.dirname, "..");
const UNIVERSE = `"a" | "b" | "c"`;
// One session per probe: the tests share no language-server state (open
// documents, project membership), so they pass in any order.
interface LabelsProbe {
readonly name: string;
readonly factory: "getPrimitiveUnionMatcher" | "getPrimitiveUnionMatcherW";
readonly body: string;
readonly universe?: string;
readonly tail?: string;
}
const labelsFor = ({
name,
factory,
body,
universe = UNIVERSE,
tail = "",
}: LabelsProbe): Promise<readonly string[]> => {
const session = new LspSession(REPO_ROOT);
const target: CompletionTarget = {
file: `src/__autocomplete_${name}.ts`,
source: [
`import { ${factory} } from "./index.ts";`,
`const m = ${factory}<${universe}>()({`,
body,
`}${tail});`,
"",
].join("\n"),
};
return session
.completionLabelsAt(target)
.then((result) => result.labels)
.finally(() => session.close());
};
test("autocomplete: an exhaustive pattern requires the universe", () => {
// Arrange
const name = "getPrimitiveUnionMatcher_fresh";
// Act
const labels = labelsFor({
name,
factory: "getPrimitiveUnionMatcher",
body: " /*COMPLETE*/",
});
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["a", "b", "c"]);
});
});
test("autocomplete: handled keys drop out of the popup", () => {
// Arrange
const name = "getPrimitiveUnionMatcher_after_key";
// Act
const labels = labelsFor({
name,
factory: "getPrimitiveUnionMatcher",
body: " a: () => 1,\n /*COMPLETE*/",
});
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["b", "c"]);
});
});
test("autocomplete: a fallback makes the remaining keys optional", () => {
// Arrange
const name = "getPrimitiveUnionMatcher_with_fallback";
// Act
const labels = labelsFor({
name,
factory: "getPrimitiveUnionMatcher",
body: " /*COMPLETE*/",
tail: ", () => 0",
});
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["a?", "b?", "c?"]);
});
});
test("autocomplete: with a fallback, handled keys stay optional", () => {
// Arrange
const name = "getPrimitiveUnionMatcher_with_fallback_after_key";
// Act
const labels = labelsFor({
name,
factory: "getPrimitiveUnionMatcher",
body: " a: () => 1,\n /*COMPLETE*/",
tail: ", () => 0",
});
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["b?", "c?"]);
});
});
test("autocomplete: `getPrimitiveUnionMatcherW` offers the same popup as `getPrimitiveUnionMatcher`", () => {
// Arrange
const name = "getPrimitiveUnionMatcherW_fresh";
// Act
const labels = labelsFor({
name,
factory: "getPrimitiveUnionMatcherW",
body: " /*COMPLETE*/",
});
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["a", "b", "c"]);
});
});
test("autocomplete: `getPrimitiveUnionMatcherW` also offers optional keys with a fallback", () => {
// Arrange
const name = "getPrimitiveUnionMatcherW_with_fallback";
// Act
const labels = labelsFor({
name,
factory: "getPrimitiveUnionMatcherW",
body: " /*COMPLETE*/",
tail: ", () => 0",
});
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["a?", "b?", "c?"]);
});
});
test("autocomplete: boolean and nullish keys are offered by name", () => {
// Arrange
const name = "getPrimitiveUnionMatcher_boolean_nullish";
// Act
const labels = labelsFor({
name,
factory: "getPrimitiveUnionMatcher",
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 = "getPrimitiveUnionMatcher_boolean_after_key";
// Act
const labels = labelsFor({
name,
factory: "getPrimitiveUnionMatcher",
universe: "boolean | null | undefined",
body: " true: () => 1,\n /*COMPLETE*/",
});
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["false", "null", "undefined"]);
});
});