13 Commits
Author SHA1 Message Date
tmu 11d364e187 🚀 Release 0.8.0
CI / release-gate (push) Successful in 3s
CI / build (push) Successful in 34s
CI / maintain (push) Successful in 15s
CI / publish (push) Failing after 19s
2026-09-23 17:42:32 +00:00
tmu 8dc0b95320 🔀 Merge fix/union-valued-discriminant into main 2026-09-23 17:37:37 +00:00
tmu 7b90f898d3 ✅ Cover property-union autocomplete and rejection
Add property-union tests for the completion popup, a broad value in the
union, and value/stringification collisions. Rename the existing
property-union tests to a `property union:` prefix so they can be
selected with `--test-name-pattern`, and extend the autocomplete helper
with a `key` option so a probe can complete on a property other than
`kind`.
2026-09-23 16:32:16 +00:00
tmu 1bdf7f0315 🐛 Reject mixed literal and broad universes
`UnsupportedReason` tested `IsLiteral<PatternKey<T>> extends false`.
`IsLiteral` is `boolean` for a union that mixes a literal with a broad
type (`"a" | \`x-${number}\``), so `boolean extends false` is false and
the mix was accepted. Test `extends true` instead, which rejects it.

Found while adding property-union broad-universe coverage; the gate is
shared with the primitive-union matcher.
2026-09-23 16:32:09 +00:00
tmu 55bf6c24a7 🐛 Narrow union-valued and optional discriminants
The tagged-union matcher selected handler parameters with
`Extract<T, Record<K, V>>`, which only keeps a member whose
discriminant is a singleton literal. A property that is itself a
union (`{ color: "red" | "green" | "blue" }`) or optional
(`{ type?: "x" }`) matched no member, so every handler received
`never`, and the fallback saw the whole shape instead of the
unhandled tags.

Replace the selector with `Narrowed`, which distributes over `T`,
drops a member whose `K` cannot take the tag, and narrows `K`. The
`T[K] extends V` fast path keeps an exact member (a discriminated
union's declared interface) untouched. The fallback reuses
`Narrowed` over `Exclude<Tags, HandledTags>`, so a union-valued
property narrows to the unhandled tags rather than the whole shape.

Matching a defined tag on an optional property makes the key
required (`{ type: "x" }`); the `undefined` tag yields
`{ type?: never }` under `exactOptionalPropertyTypes` (absence) or
`{ type?: undefined }` when the property admits an explicit
`undefined`.
2026-09-23 16:04:00 +00:00
tmu e7b5c0284d 🔀 Merge chore/prune-backlog into main 2026-09-23 15:27:05 +00:00
tmu 013bfa883b 📝 Prune the backlog; document the LSP shutdown fix
Remove every done/cancelled backlog item; the reasons they recorded are
already in development/ (library.md, testing.md, tooling.md, workflow.md)
and git history is the archive.

The one exception was the TS 7 LSP shutdown workaround, which lived only in
a code comment. Record it under development/testing.md § Autocomplete
(Known issue) before dropping the bug item.
2026-09-23 15:12:54 +00:00
tmu d99d84d387 🚀 Release 0.7.1
CI / release-gate (push) Successful in 2s
CI / build (push) Successful in 34s
CI / maintain (push) Successful in 15s
CI / publish (push) Failing after 17s
2026-09-23 14:56:59 +00:00
tmu 02f64f804e 🔀 Merge fix/knip-library-entry into main 2026-09-23 14:56:15 +00:00
tmu cbaed8fabc 🐛 Stop knip reporting the source entry
Listing scripts/*.ts in knip's `entry` replaced its default entry
detection, which derives the public entry from package.json `exports`.
Adding the CLI scripts therefore dropped the library entry, so knip
resolved the package through dist/index.js and flagged the unreferenced
src/index.ts as unused. Name the source entry alongside the scripts.

Record the rationale in development/tooling.md.
2026-09-23 14:55:27 +00:00
tmu 410903198e 🔀 Merge chore/upgrade-deps into main 2026-09-23 14:51:49 +00:00
tmu 2e4262383c ⬆️ Upgrade dependencies
Bump every direct dependency to the latest registry version: cspell
10.3.3, knip 6.38.0, oxfmt 0.70.0, oxlint 1.85.0, oxlint-tsgolint
7.0.2002 and type-fest 5.10.0, plus their transitive updates. oxfmt is
the only range widened (^0.68.0 -> ^0.70.0); the rest moved within
their existing semver ranges.

`npm run maintain:outdated` is now clean and `npm run verify` is green
with no rule or format fallout. `maintain:knip` still reports the
pre-existing `src/index.ts` false positive (dist-only `exports`), which
predates this bump.
2026-09-23 14:50:29 +00:00
tmu a8f1a05db2 🚀 Release 0.7.0
CI / release-gate (push) Successful in 2s
CI / build (push) Successful in 34s
CI / maintain (push) Failing after 16s
CI / publish (push) Failing after 17s
2026-09-23 14:34:51 +00:00
12 changed files with 975 additions and 518 deletions

No files matched your search

+19 -2
View File
@@ -7,9 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.8.0] - 2026-09-23
- reject a universe that mixes a literal with a broad type (e.g.
`"a" | \`x-${number}\``), which the finite-literal gate let through
- narrow the tagged-union matcher's handler parameters for a union-valued or
optional discriminant, and its fallback to the unhandled tags, instead of
passing `never`
## [0.7.1] - 2026-09-23
- upgrade dependencies
## [0.7.0] - 2026-09-23
- reject broad universes (`string`, `number`, template literals) and
value/stringification collisions (`true | "true"`, `1 | "1"`) at the factory
- type handler parameters by the matched member (`Member<T, K>`), so a
- type handler parameters by the matched member, so a
standalone `"true"` universe is typed `"true"` rather than `true`
## [0.6.0] - 2026-09-22
@@ -80,7 +94,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- basic setup
[Unreleased]: https://gitea.e1nsnull.de/tmu/tiny-pattern-ts/compare/0.6.0...main
[Unreleased]: https://gitea.e1nsnull.de/tmu/tiny-pattern-ts/compare/0.8.0...main
[0.8.0]: https://gitea.e1nsnull.de/tmu/tiny-pattern-ts/compare/0.7.1...0.8.0
[0.7.1]: https://gitea.e1nsnull.de/tmu/tiny-pattern-ts/compare/0.7.0...0.7.1
[0.7.0]: https://gitea.e1nsnull.de/tmu/tiny-pattern-ts/compare/0.6.0...0.7.0
[0.6.0]: https://gitea.e1nsnull.de/tmu/tiny-pattern-ts/compare/0.5.0...0.6.0
[0.5.0]: https://gitea.e1nsnull.de/tmu/tiny-pattern-ts/compare/0.4.0...0.5.0
[0.4.0]: https://gitea.e1nsnull.de/tmu/tiny-pattern-ts/compare/0.3.0...0.4.0
+2 -60
View File
@@ -6,17 +6,6 @@ Backlog and tracking for tiny-pattern-ts. Managed in vscode-todotasks format.
Setup:
☐ Split off template into separate package => pi --session 01a07dde-7050-7054-bb36-1606d7eb2bc3 @low
✔ straighten oxc rules @done
✔ oxc forbids ternary => remove oxc rule @done
✔ oxc wants comments to start comments with a capital letter => remove oxc rule @done
✔ there already exists a /* */ block comment in primitive.ts, => change to multi-line comment @done
✔ Remove example code files and its documentation and its exports from index.ts @high @done
✔ remove src/match.ts and its documentation @high @done
✔ remove src/pattern.ts and its documentation @high @done
✔ remove src/index.test.ts and its documentation @high @done
✔ exports from `src/index.ts` should only be the public API surface @done
v1.0:
☐ API surface is stable and fully typed
@@ -27,54 +16,11 @@ v1.0:
☐ Achieve 100% branch coverage on `src/primitive-union.ts`
☐ Achieve 100% branch coverage on `src/index.ts`
Testing:
✔ Cover autocomplete with real completion test cases in the suite @medium @done
→ `src/util/__tests__/lsp-completion.ts` (`#test-utils/…`) is the helper; the suite asserts its labels (see development/testing.md § Autocomplete)
→ wire it into `node --test` so a test asserts the offered labels
→ note: `Parameters<typeof factory>[0]` resolves only the *last* overload; use `@ts-expect-error` call sites for factory negatives, not `not.toExtend<Parameters<…>>`
✔ Drive the LSP completion helper through the LSP protocol library instead of a hand-rolled JSON-RPC client @medium @done
✔ Add `vscode-languageserver-protocol` and record the tooling decision @done
✔ Rewrite `src/util/__tests__/lsp-completion.ts` onto `createMessageConnection` and typed requests @done
✔ Update `development/testing.md § Autocomplete` for the new client @done
✔ Run `npm run verify` and check the task off @done
✘ Test a literal union widened with `(string & {})` — `"red" | "green" | "yellow" | (string & {})` @medium @cancelled
→ broad universes are rejected; the rejection is covered by the broad-universe gate tests
✔ Type hole when using broad types like string as a universe @high @done
→ decided: broad universes are rejected at the factory, so the exhaustive overload can always be proven
→ value/stringification collisions (`true | "true"`, `1 | "1"`) are rejected too; handler params are typed by `Member<T, K>`
→ see development/library.md § Supported universes
Matcher:
✔ Clean up: adopt the 3-overload matcher (`src/prototype-ac2.ts`) and delete the prototypes @high @done
→ `getMatcher` / `getMatcherW`, each with overloads `ExhaustiveLoose` → `Fallback` → `Handlers` (order is load-bearing)
→ fold into `src/primitive.ts` / the public API; drop `src/prototype*.ts`
✔ `_` should receive only the unhandled `T` keys, not all of `T` @medium @done
→ the fallback is now a second argument: `(handlers, (s) => …)`, `s: Exclude<T, keyof handlers>`
✔ A fallback for an already-exhaustive handler map must be a compile error @medium @done
→ rejected by an F-bounded constraint on `Handled` (checked *after* inference); a conditional in the fallback parameter is evaluated too early and breaks contextual typing
✔ Implement matcher with similar API like matcher from primitive.ts @high @done
→ `getTaggedUnionMatcher` / `getTaggedUnionMatcherW`, curried on the discriminant key
→ fallback is the second argument; `_` removed
✔ Rename `primitive` to `primitive-union` and `getMatcher` to `getPrimitiveMatcher` @medium @done
→ `src/primitive.ts` / `src/primitive.test.ts` → `primitive-union.*`
→ `getMatcherW` → `getPrimitiveMatcherW` for symmetry with the tagged-union pair
→ update `src/index.ts`, `development/library.md` and any README references
→ shipped as `getPrimitiveUnionMatcher` / `getPrimitiveUnionMatcherW`; kept `Union` for symmetry with the tagged-union pair
☐ when using a union type as a property, the current behavior of tagged union matcher is
✔ when using a union type as a property, the current behavior of tagged union matcher is @done
to pass never to handler parameters
→ new matcher function needed or can be fixed in tagged union matcher
☐ optional discriminant (`{ type?: "x" }`) is the same hole: the boolean/nullish change now admits the `undefined` tag, so the factory accepts the key, but `Extract<T, Record<K, V>>` still passes `never` to both the `x` and `undefined` handlers
Bugs:
✔ TS 7 LSP server logs `context canceled` on stderr at shutdown @done
→ `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 @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)
✔ Allow boolean, null and undefined discriminant values in tagged-union patterns @medium @done
→ moved the `PatternKey` / `PatternParam` projection to `matcher-shared.ts` and keyed the tagged-union handler map through it; see development/library.md § Tagged-union matcher
✔ optional discriminant (`{ type?: "x" }`) is the same hole: the boolean/nullish change now admits the `undefined` tag, so the factory accepts the key, but `Extract<T, Record<K, V>>` still passes `never` to both the `x` and `undefined` handlers @done
Documentation:
☐ Bring README.md back to its previous form — synopsis and examples restored, in the correct place
@@ -84,12 +30,8 @@ Documentation:
☐ Add comparison section vs. other TS pattern-matching libs in Readme.md
☐ Write migration guide for users coming from discriminated unions
☐ Create backlog tasks for implementation
✔ Document the matcher design paths in `development/` — union vs overload merge, inferred universe (`NoInfer`), conditional `RequireKeys`, cases-first — and why each was abandoned @done
☐ Validate code fences in Markdown (start with README.md) — compile the TypeScript examples against `src/` so the docs cannot drift from the API
Workflow:
✔ Resolve the finish/push tension: `create:finish` leaves `main` ahead of its upstream while `create:branch` refuses until `main` matches upstream — decide whether `finish` should push or `branch` should compare only `BEHIND` (see development/workflow.md) @done
Maintenance:
☐ Serve CI coverage over a tiny self-hosted webserver (replace the zip artifact) @low
☐ Explore serving coverage for non-tag pushes (e.g. `main/coverage`, PR previews) @low
+21 -6
View File
@@ -145,6 +145,10 @@ inversion: the handler parameter is the member(s) of `T` whose `PatternKey` is
object satisfy the exhaustive overload and reaches the `dispatch` throw.
Rejecting at the boundary avoids threading an open/closed branch through
`Handlers`, `Fallback` and `MustBePartial`.
- **The finite-literal predicate is `IsLiteral<PatternKey<T>> extends true`.**
`IsLiteral` is `boolean` for a union that mixes a literal with a broad type
(`"a" | \`x-${number}\``), so `extends false`would treat the mix as
supported;`extends true` is the check that rejects it.
- **Collisions are rejected, not merged.** `Member<T, K>` would be sound (the
handler gets the union), but the API is one handler per member; rejecting
keeps `Member` a singleton and the remainder exact.
@@ -208,16 +212,27 @@ The key is a separate call because `K` is inferred from its literal argument and
#### Why
- **Same fallback/remainder machinery as the primitive-union matcher.** `HandledMembers`
maps the handled tags to their members and `Exclude<T, …>` is the fallback's
parameter; the redundant-fallback guard is the same F-bounded constraint. Only
the "universe" changes — `T`'s members instead of primitive values.
- **Same fallback/remainder machinery as the primitive-union matcher.** `HandledTags`
recovers the tag values the map handled (`Member<Tags, keyof Handled>`) and
`Narrowed<T, K, Exclude<Tags, …>>` is the fallback's parameter; the
redundant-fallback guard is the same F-bounded constraint. Only the "universe"
changes — `T`'s members instead of primitive values.
- **`T extends object`, not `Record<PropertyKey, unknown>`.** An `interface` has
no implicit index signature, so the `Record` constraint would reject
interface-based unions. The runtime reads the tag off `object` with one
assertion, the tagged twin of the primitive-union dispatch's `shape as string | number`.
- **`MapTaggedUnion` distributes with `Extract`.** A duplicated tag yields a
union of members instead of dropping one.
- **`Narrowed` distributes over `T`, narrowing `K` to the tag.** A member whose
`K` cannot take the tag drops out; a duplicated tag yields a union of members
instead of dropping one. `T[K] extends V` returns the exact member (a
discriminated union's declared interface) untouched, so the mapped form only
handles a property that is itself a union.
- **A union-valued or optional discriminant is supported.** A single shape whose
property is a union (`{ color: "red" | "green" | "blue" }`) is narrowed per
handler instead of being passed `never`. Matching a defined tag on an optional
property (`{ type?: "x" }`) proves the key is present, so it becomes required
(`{ type: "x" }`); the `undefined` tag narrows it to `{ type?: never }` under
`exactOptionalPropertyTypes` (absence) or `{ type?: undefined }` when the
property explicitly admits `undefined`.
- **A `boolean` / `null` / `undefined` tag goes through the shared
`PatternKey` / `Member` projection.** `Discriminated` admits those tags
(they are in `Tag`), but they cannot key a mapped type, so the handler map is
+5
View File
@@ -198,6 +198,11 @@ the CLI is for manual inspection.
delay is needed.
- The server answers some requests with a string id (`client/registerCapability`);
the client must tolerate `string | number` ids or the server stalls.
- `LspSession.close()` sends `shutdown` and then closes stdin instead of
sending `exit`. The TS 7 Go server's `handleExit` returns `io.EOF`, cancelling
the background context while a watch update is still in flight, and logs a
bare `context canceled` before exiting 1; EOF on stdin exits 0 with no output.
The kill stays as a fallback for a server that does not exit.
## Known issues
+22
View File
@@ -196,6 +196,28 @@ joining the oxfmt-superseded rules already off.
are part of the public API.
- The narrower scope keeps the signal high without config-file boilerplate.
### `knip` lists `src/index.ts` as an entry
#### Decision (2026-09)
`knip.json` declares `"entry": ["src/index.ts", "scripts/*.ts"]`.
#### Why
- Supplying `entry` **replaces** knip's default entry detection, which otherwise
derives the public entry from `package.json` `exports`. Adding `scripts/*.ts`
there therefore dropped the library entry, so knip resolved the package through
its `dist/index.js` output and reported the unreferenced source entry file
`src/index.ts` as an unused file.
- Naming the source entry restores the link between the public API and the
source graph without pointing knip at build output.
#### Rejected
- `paths` mapping `dist/index.*` back to `src/index.ts`: more config to model a
relation the explicit entry states directly, and it would break whenever the
build layout changes.
### `maintain:outdated` ignores `@types/node`
#### Decision (2026-09)
+1 -1
View File
@@ -1,5 +1,5 @@
{
"$schema": "./node_modules/knip/schema.json",
"entry": ["scripts/*.ts"],
"entry": ["src/index.ts", "scripts/*.ts"],
"ignoreDependencies": ["@runwisp/pubv"]
}
+424 -424
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "tiny-pattern-ts",
"version": "0.6.0",
"version": "0.8.0",
"description": "Pattern matching for TypeScript/ESM environments (F#-style, not regex)",
"keywords": [
"adt",
@@ -83,7 +83,7 @@
"expect-type": "1.4.0",
"knip": "^6.34.0",
"lefthook": "^2.1.12",
"oxfmt": "^0.68.0",
"oxfmt": "^0.70.0",
"oxlint": "^1.83.0",
"oxlint-tsgolint": "^7.0.2001",
"publint": "^0.3.24",
+5 -5
View File
@@ -62,11 +62,11 @@ export type Collisions<T> = Extract<T, Stringified<T>>;
// universe is a finite union of literals with no value/stringification
// collision: only then can `PatternKey` be inverted unambiguously.
export type UnsupportedReason<T extends Matchable> =
IsLiteral<PatternKey<T>> extends false
? "broad types like string, number and template literals are not supported"
: [Collisions<T>] extends [never]
? never
: `a value and its stringification collide. Value is "${Collisions<T> & string}"`;
IsLiteral<PatternKey<T>> extends true
? [Collisions<T>] extends [never]
? never
: `a value and its stringification collide. Value is "${Collisions<T> & string}"`
: "broad types like string, number and template literals are not supported";
// The diagnostic for an unsupported universe. Extends `HandlerMap` so the
// implementation's `handlers: HandlerMap` stays assignable when the gate is
+2
View File
@@ -528,6 +528,8 @@ test("getPrimitiveUnionMatcher: a broad universe is rejected", () => {
getPrimitiveUnionMatcher<number>()({ 1: () => 1 });
// @ts-expect-error a template literal is open
getPrimitiveUnionMatcher<`a${string}`>()({ a: () => 1 });
// @ts-expect-error a literal mixed with a template literal is open
getPrimitiveUnionMatcher<"a" | `x-${number}`>()({ 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
+440 -1
View File
@@ -892,6 +892,358 @@ test("getTaggedUnionMatcher: the maximum illegal tag universe is rejected", () =
});
});
// ============================================================================
// Property unions
// ============================================================================
test("property union: narrows each handler", () => {
// Arrange — one shape, not a union of variants; `color` is a union.
interface Paint {
readonly color: "red" | "green" | "blue";
readonly value: number;
}
const factory = getTaggedUnionMatcher<Paint>()("color");
// Act
const describe = factory({
red: (s) => {
expectTypeOf(s).toEqualTypeOf<{
readonly color: "red";
readonly value: number;
}>();
assert.equal(s.color, "red");
return s.value;
},
green: (s) => {
expectTypeOf(s).toEqualTypeOf<{
readonly color: "green";
readonly value: number;
}>();
assert.equal(s.color, "green");
return s.value;
},
blue: (s) => {
expectTypeOf(s).toEqualTypeOf<{
readonly color: "blue";
readonly value: number;
}>();
assert.equal(s.color, "blue");
return s.value;
},
});
// Assert
expectTypeOf(describe).toEqualTypeOf<(shape: Paint) => number>();
assert.equal(describe({ color: "red", value: 1 }), 1);
assert.equal(describe({ color: "green", value: 2 }), 2);
assert.equal(describe({ color: "blue", value: 3 }), 3);
});
test("property union: a fallback receives the unhandled values", () => {
// Arrange
interface Paint {
color: "red" | "green" | "blue";
value: number;
}
const factory = getTaggedUnionMatcher<Paint>()("color");
// Act
const describe = factory(
{
red: (s) => {
expectTypeOf(s).toEqualTypeOf<{
color: "red";
value: number;
}>();
assert.equal(s.color, "red");
return 1 as const;
},
},
(s) => {
expectTypeOf(s).toEqualTypeOf<{
color: "green" | "blue";
value: number;
}>();
assert.ok(s.color === "green" || s.color === "blue");
return 2 as const;
},
);
// Assert
expectTypeOf(describe).toEqualTypeOf<(shape: Paint) => 1 | 2>();
assert.equal(describe({ color: "red", value: 1 }), 1);
assert.equal(describe({ color: "green", value: 2 }), 2);
assert.equal(describe({ color: "blue", value: 3 }), 2);
});
test("property union: a numeric property narrows each handler", () => {
// Arrange
interface Version {
code: 1 | 2 | 3;
value: number;
}
const factory = getTaggedUnionMatcher<Version>()("code");
// Act
const describe = factory({
1: (s) => {
expectTypeOf(s).toEqualTypeOf<{ code: 1; value: number }>();
assert.equal(s.code, 1);
return 1;
},
2: (s) => {
expectTypeOf(s).toEqualTypeOf<{ code: 2; value: number }>();
assert.equal(s.code, 2);
return 2;
},
3: (s) => {
expectTypeOf(s).toEqualTypeOf<{ code: 3; value: number }>();
assert.equal(s.code, 3);
return 3;
},
});
// Assert
expectTypeOf(describe).toEqualTypeOf<(shape: Version) => number>();
assert.equal(describe({ code: 1, value: 10 }), 1);
assert.equal(describe({ code: 2, value: 20 }), 2);
assert.equal(describe({ code: 3, value: 30 }), 3);
});
test("property union: an optional property is required for a defined tag", () => {
// Arrange — `type?` is `"x" | undefined`; both handlers must be typed,
// and matching `"x"` proves the key is present, so `type` becomes required.
interface Maybe {
type?: "x";
value: number;
}
const factory = getTaggedUnionMatcher<Maybe>()("type");
// Act
const describe = factory({
x: (s) => {
expectTypeOf(s).toEqualTypeOf<{ type: "x"; value: number }>();
assert.equal(s.type, "x");
return 1;
},
undefined: (s) => {
// The input only allows absence (exactOptionalPropertyTypes), so
// the `undefined` tag narrows the key to never-present.
expectTypeOf(s).toEqualTypeOf<{ type?: never; value: number }>();
assert.equal(s.type, undefined);
return 2;
},
});
// Assert
expectTypeOf(describe).toEqualTypeOf<(shape: Maybe) => number>();
assert.equal(describe({ type: "x", value: 1 }), 1);
assert.equal(describe({ value: 2 }), 2);
});
test("property union: an optional fallback receives the undefined tag", () => {
// Arrange
interface Maybe {
type?: "x";
value: number;
}
const factory = getTaggedUnionMatcher<Maybe>()("type");
// Act
const describe = factory(
{
x: (s) => {
expectTypeOf(s).toEqualTypeOf<{ type: "x"; value: number }>();
assert.equal(s.type, "x");
return 1 as const;
},
},
(s) => {
expectTypeOf(s).toEqualTypeOf<{
type?: never;
value: number;
}>();
assert.equal(s.type, undefined);
return 2 as const;
},
);
// Assert
expectTypeOf(describe).toEqualTypeOf<(shape: Maybe) => 1 | 2>();
assert.equal(describe({ type: "x", value: 1 }), 1);
assert.equal(describe({ value: 2 }), 2);
});
test("property union: explicit `undefined` stays distinct from absence", () => {
// Arrange — `type?: "x" | undefined` admits an explicit `undefined`, unlike
// the bare optional above; the two representations must not be conflated.
interface Explicit {
type?: "x" | undefined;
value: number;
}
const factory = getTaggedUnionMatcher<Explicit>()("type");
// Act
const describe = factory({
x: (s) => {
expectTypeOf(s).toEqualTypeOf<{ type: "x"; value: number }>();
assert.equal(s.type, "x");
return 1;
},
undefined: (s) => {
expectTypeOf(s).toEqualTypeOf<{
type?: undefined;
value: number;
}>();
assert.equal(s.type, undefined);
return 2;
},
});
// Assert
expectTypeOf(describe).toEqualTypeOf<(shape: Explicit) => number>();
assert.equal(describe({ type: "x", value: 1 }), 1);
assert.equal(describe({ type: undefined, value: 2 }), 2);
assert.equal(describe({ value: 3 }), 2);
});
test("property union: a union-valued member is split, not dropped", () => {
// A member whose tag is itself a union sits beside a singleton-tag member.
// Selecting members with `Extract<T, Record<K, V>>` keeps only the
// singleton; the distributive narrowing must keep both sides of the
// union-valued member.
// Arrange
type Mixed = { kind: "a"; a: number } | { kind: "a" | "b"; b: number };
const factory = getTaggedUnionMatcher<Mixed>()("kind");
// Act
const describe = factory({
a: (s) => {
expectTypeOf(s).toEqualTypeOf<
{ kind: "a"; a: number } | { kind: "a"; b: number }
>();
assert.equal(s.kind, "a");
return 1;
},
b: (s) => {
expectTypeOf(s).toEqualTypeOf<{ kind: "b"; b: number }>();
assert.equal(s.kind, "b");
return 2;
},
});
// Assert
expectTypeOf(describe).toEqualTypeOf<(shape: Mixed) => number>();
assert.equal(describe({ kind: "a", a: 1 }), 1);
assert.equal(describe({ kind: "a", b: 2 }), 1);
assert.equal(describe({ kind: "b", b: 3 }), 2);
});
test("property union: getTaggedUnionMatcherW widens the returns", () => {
// Arrange
interface Paint {
color: "red" | "green" | "blue";
value: number;
}
const factory = getTaggedUnionMatcherW<Paint>()("color");
// Act
const describe = factory({
red: (s) => {
expectTypeOf(s).toEqualTypeOf<{ color: "red"; value: number }>();
assert.equal(s.color, "red");
return "r" as const;
},
green: (s) => {
expectTypeOf(s).toEqualTypeOf<{ color: "green"; value: number }>();
assert.equal(s.color, "green");
return 1 as const;
},
blue: (s) => {
expectTypeOf(s).toEqualTypeOf<{ color: "blue"; value: number }>();
assert.equal(s.color, "blue");
return true as const;
},
});
// Assert
expectTypeOf(describe).toEqualTypeOf<(shape: Paint) => "r" | 1 | true>();
assert.equal(describe({ color: "red", value: 1 }), "r");
assert.equal(describe({ color: "green", value: 2 }), 1);
assert.equal(describe({ color: "blue", value: 3 }), true);
});
test("property union: enforces its contract", () => {
// Arrange
interface Paint {
color: "red" | "green" | "blue";
value: number;
}
const factory = getTaggedUnionMatcher<Paint>()("color");
// Act / Assert — the calls below must not compile
factory({
red: () => 1,
green: () => 2,
blue: () => 3,
// @ts-expect-error `yellow` is not a value of `color`
yellow: () => 4,
});
// @ts-expect-error a gap without a fallback is not exhaustive
factory({ red: () => 1 });
// @ts-expect-error a fallback is redundant once every value is handled
factory({ red: () => 1, green: () => 2, blue: () => 3 }, () => 0);
});
test("property union: a broad value in the union is rejected", () => {
// Arrange — the property is a union, but not a finite union of literals: a
// template literal cannot be proven exhaustive.
interface Template {
kind: "a" | `x-${number}`;
a: number;
}
// Act / Assert — the calls below must not compile
// @ts-expect-error a template literal is not a finite literal
getTaggedUnionMatcher<Template>()("kind")({ a: () => 1 });
// @ts-expect-error the widening factory rejects broad values too
getTaggedUnionMatcherW<Template>()("kind")({ a: () => 1 });
});
test("property union: a value/stringification collision is rejected", () => {
// Arrange — one property holding both a value and its stringification; both
// would key the same handler.
interface BooleanColliding {
kind: "true" | true;
a: number;
}
interface NumericColliding {
kind: "1" | 1;
a: number;
}
// Act / Assert — the calls below must not compile
// @ts-expect-error `true` collides with the string tag `"true"`
getTaggedUnionMatcher<BooleanColliding>()("kind")({ true: () => 1 });
// @ts-expect-error the number tag `1` collides with the string tag `"1"`
getTaggedUnionMatcher<NumericColliding>()("kind")({ "1": () => 1 });
// @ts-expect-error the widening factory rejects the collision too
getTaggedUnionMatcherW<BooleanColliding>()("kind")({ true: () => 1 });
});
test("property union: a collision is rejected beside legal members", () => {
// Arrange — the map is otherwise complete, so only the collision can make
// it invalid.
interface Colliding {
kind: "true" | true | "a";
a: number;
}
// Act / Assert — the call below must not compile
// @ts-expect-error `true` collides with the string tag `"true"`
getTaggedUnionMatcher<Colliding>()("kind")({ true: () => 1, a: () => 2 });
});
// ============================================================================
// Dispatch — runtime behavior
// ============================================================================
@@ -935,6 +1287,7 @@ interface LabelsProbe {
readonly tail?: string;
readonly typeName?: string;
readonly typeSource?: string;
readonly key?: string;
}
const labelsFor = ({
@@ -944,6 +1297,7 @@ const labelsFor = ({
tail = "",
typeName = "Shape",
typeSource = SHAPE_SOURCE,
key = "kind",
}: LabelsProbe): Promise<readonly string[]> => {
const session = new LspSession(REPO_ROOT);
const target: CompletionTarget = {
@@ -951,7 +1305,7 @@ const labelsFor = ({
source: [
`import { ${factory} } from "./index.ts";`,
typeSource,
`const m = ${factory}<${typeName}>()("kind")({`,
`const m = ${factory}<${typeName}>()("${key}")({`,
body,
`}${tail});`,
"",
@@ -1038,6 +1392,91 @@ test("autocomplete: boolean and nullish tags are offered by name", () => {
});
});
// A single shape whose property is a union: the popup is still keyed by the
// property's values, not by the members of a union type.
const PALETTE_SOURCE = `interface Palette { color: "red" | "green" | "blue"; value: number }`;
const FLAG_SOURCE = `interface Flag { kind: true | false | null | undefined; a: number }`;
test("property union: autocomplete offers the property's values", () => {
// Arrange
const name = "property_union_fresh";
// Act
const labels = labelsFor({
name,
factory: "getTaggedUnionMatcher",
typeName: "Palette",
typeSource: PALETTE_SOURCE,
key: "color",
body: " /*COMPLETE*/",
});
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["blue", "green", "red"]);
});
});
test("property union: autocomplete drops a handled value", () => {
// Arrange
const name = "property_union_after_key";
// Act
const labels = labelsFor({
name,
factory: "getTaggedUnionMatcher",
typeName: "Palette",
typeSource: PALETTE_SOURCE,
key: "color",
body: " red: () => 1,\n /*COMPLETE*/",
});
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["blue", "green"]);
});
});
test("property union: autocomplete makes the remaining values optional with a fallback", () => {
// Arrange
const name = "property_union_with_fallback";
// Act
const labels = labelsFor({
name,
factory: "getTaggedUnionMatcher",
typeName: "Palette",
typeSource: PALETTE_SOURCE,
key: "color",
body: " /*COMPLETE*/",
tail: ", () => 0",
});
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["blue?", "green?", "red?"]);
});
});
test("property union: autocomplete offers boolean and nullish values by name", () => {
// Arrange
const name = "property_union_boolean_nullish";
// Act
const labels = labelsFor({
name,
factory: "getTaggedUnionMatcher",
typeName: "Flag",
typeSource: FLAG_SOURCE,
body: " /*COMPLETE*/",
});
// Assert
return labels.then((result) => {
assert.deepEqual([...result], ["false", "null", "true", "undefined"]);
});
});
// `Mixed` has two common keys, but `id`'s value is not a tag, so only `kind`
// may serve as the discriminant.
const MIXED_SOURCE = `type Mixed = { id: Date; kind: "a"; a: number } | { id: Date; kind: "b"; b: number };`;
+32 -17
View File
@@ -1,4 +1,4 @@
import type { Exact, UnknownRecord } from "type-fest";
import type { Exact, SetRequired, UnknownRecord } from "type-fest";
import type {
HandlerMap,
@@ -28,34 +28,49 @@ type Discriminated<T extends object> = {
[K in keyof T]: T[K] extends Matchable ? K : never;
}[keyof T];
// The member(s) of `T` tagged `V`. `Extract` distributes over the union, so a
// The member(s) of `T` narrowed to the tag(s) `V`. Distributes over `T`, so a
// duplicated tag maps to a union of members rather than silently dropping one.
// A member whose `K` cannot take `V` drops out; the rest have `K` narrowed to
// `Extract<T[K], V>`. `T[K] extends V` keeps an exact member (a discriminated
// union's declared interface) untouched, so only a property that is itself a
// union — or optional — goes through the mapped form. `SetRequired` makes `K`
// required unless `V` admits `undefined`: a defined tag yields `{ type: "x" }`,
// while the `undefined` tag keeps `{ type?: never }` (absence) or
// `{ type?: undefined }` when the property admits an explicit `undefined`.
// Keyed by `PatternKey`, so `boolean`/`null`/`undefined` tags can key a mapped
// type; `Member` inverts the projection against the tag set to recover the
// member.
// type; `Member` inverts the projection against the tag set to recover the tag.
type Narrowed<T extends object, K extends keyof T, V> = T extends object
? [Extract<T[K], V>] extends [never]
? never
: T[K] extends V
? T
: undefined extends V
? { [P in keyof T]: P extends K ? Extract<T[P], V> : T[P] }
: SetRequired<
{ [P in keyof T]: P extends K ? Extract<T[P], V> : T[P] },
K
>
: never;
type MapTaggedUnion<T extends object, K extends keyof T> = {
[P in PatternKey<Tags<T, K>>]: Extract<T, Record<K, Member<Tags<T, K>, P>>>;
[P in PatternKey<Tags<T, K>>]: Narrowed<T, K, Member<Tags<T, K>, P>>;
};
type Handlers<T extends object, K extends keyof T, R> = {
[P in PatternKey<Tags<T, K>>]: UnaryFn<MapTaggedUnion<T, K>[P], R>;
};
// The members `Handled` covers. Mapping over the projected keys keeps every
// index within `MapTaggedUnion`'s keys, and the conditional drops a stray key
// outside `T` so it cannot widen the remainder. The remainder is
// `Exclude<T, …>`, mirroring the primitive-union matcher's
// `Exclude<T, Member<T, keyof Handled>>`.
type HandledMembers<T extends object, K extends keyof T, Handled> = {
[P in PatternKey<Tags<T, K>>]: P extends keyof Handled
? MapTaggedUnion<T, K>[P]
: never;
}[PatternKey<Tags<T, K>>];
// The tag values whose `PatternKey` is handled.
type HandledTags<T extends object, K extends keyof T, Handled> = Member<
Tags<T, K>,
keyof Handled
>;
// The fallback is a *second argument*, not a property of the handler map, so
// its parameter can be the remainder the map left uncovered. See development/library.md.
// its parameter can be the remainder the map left uncovered: the members
// narrowed to the tags the map did not handle. See development/library.md.
type Fallback<T extends object, K extends keyof T, Handled, R> = UnaryFn<
Exclude<T, HandledMembers<T, K, Handled>>,
Narrowed<T, K, Exclude<Tags<T, K>, HandledTags<T, K, Handled>>>,
R
>;