match on a union of string literals #97

Merged
sionzee merged 1 commit from closed-set-dispatch-match into main 2026-11-20 16:44:46 +01:00
Owner

Stacked on #91: the base is closed-set-dispatch, so the diff here is this PR's own commit. Merge #91 first, then retarget this PR to main.

Problem

The enums guide recommends a union of strings ("red" | "green") for plain names, but match took only an Enum. For a union, the only exhaustive forms were switch + unreachable and a Record table. The rules in #91 found these unions dispatched by hand, and had to suggest something longer than match.

Solution

match on a union of string literals (@evobug_com/safe-ts-std/enum), checked as for an enum:

  • match(command, { open: () => …, urls: () => …, help: () => … }). A missing member or a misspelled one doesn't compile.
  • _ gets the members left, as strings. On an Option of a union, the undefined handler or _ covers the missing value.
  • A plain string doesn't compile. The error message names the problem: match needs an enum or a union of string literals, not \string``.
  • Numbers are not supported. Handler keys are object keys, so a numeric code would need "0"-style keys or computed [Phase.WALK] keys. The rewrite can't handle computed keys, and either form loses the names. The docs point numeric code sets at switch + unreachable or a Record<Code, T> table.

Types: match keeps its single signature, as its comments ask.

  • The handler keys are Extract<E, Tagged>["tag"] | Extract<E, string>. A conditional KeyOf stopped TypeScript from inferring the handlers' keys, and with them every handler's parameter type. I bisected this to MatchKeys.
  • The plain-string rejection is a separate ClosedSet<V> term on the parameter, for the same reason.

Runtime: match reads typeof value === "string" ? value : value.tag, and now looks only at the handler object's own properties. A member like "toString" with no handler of its own must reach _, not Object.prototype.toString.

The build turns it into switch (value). The transform has no types, so the whole-program pass decides for each match (json::value::match_on). shape.rs records the shape of the matched value, including the value inside a dev check's wrap.

  • An enum (or Open<K>): switch on .tag, as before.
  • A union of string literals: switch on the value.
  • Type not found, in TypeScript: the call stays a runtime match, and safe-ts explain says why. The emitted TypeScript must type-check, and only a switch on .tag narrows the value for the handlers. One exception: a handler that destructures its parameter (({ radius }) =>) is on an object, so that call is lowered on .tag.
  • Type not found, in JavaScript: switch (typeof v === "string" ? v : v.tag).

To keep enum matches lowered:

  • A declared type that mentions an outer type parameter is now read with that parameter as unknown (Tree<T> is a Tree<unknown>). Before, the whole type was unknown. A type that is a bare T, or contains a mapped or conditional type, stays unknown as before.
  • Measured over the repo's match calls (examples, std tests, benches, Vue/React packages): 47 enum matches lowered on .tag before and after. 9 new union matches are lowered on the value. 1 numeric match is left as a call, and that one doesn't compile anyway.

The dev check accepts strings, and names the string with no handler (match got "close", which has no handler here (handled: open, urls)).

The rule messages from #91 now suggest match for a union of strings: exhaustive-dispatch, exhaustive-switch and string-dispatch.

Tests

  • cargo nextest run --workspace: 283 passed.
  • New transform tests:
    • the exact output for a union and for an Option of one;
    • an unknown type stays a call, and the destructuring hint;
    • explain;
    • one that runs the source and the rewrite in Node and compares the output.
  • Existing transform tests that matched on undeclared types now declare them (TYPES).
  • npm run test:std: 369 passed. Covers runtime and rewritten string matches, the toString member, and the dev check.
  • packages/std/test/enum.check.ts covers the types: exhaustive, _, undefined, misspelled members, plain string and numbers rejected. tsc -p packages/std passes, and so does npm run typecheck:emit (the emitted output type-checks).
  • node scripts/docs-typecheck.mjs: 620 examples compile. The docs examples test passes.
  • npm run bench:check: passes. match / switch, through the transform is 0.98x (limit 1.92x).

Docs

  • guide/enums.md: a new section, "Matching a union of strings", plus the tip, the dispatch section and the TypeScript enum section.
  • exhaustive-dispatch.md gets a union example. string-dispatch.md's accepted example now uses match. exhaustive-switch.md mentions match.
  • json.md's czech example uses match with _.
  • dev-checks.md, transforms.md, the skill's patterns-core.md and tool-gaps.md, and CHANGELOG.

Left out

  • Vue/React <Match> still takes an enum only (the docs say so). Use match in a computed instead.
  • A string union with the literal "undefined" or "_" as a member collides with those handler keys. It's not handled; I expect it to be rare.
  • must-use-result reports a discarded match(...) statement (it reads match's return-type alias, which is named Result). This was already the case for enums. I wrote the docs example as return match(...) and didn't change the rule.

Created with Claude Opus 5.5 in Claude Code.

Stacked on #91: the base is `closed-set-dispatch`, so the diff here is this PR's own commit. Merge #91 first, then retarget this PR to `main`. ## Problem The enums guide recommends a union of strings (`"red" | "green"`) for plain names, but `match` took only an `Enum`. For a union, the only exhaustive forms were `switch` + `unreachable` and a `Record` table. The rules in #91 found these unions dispatched by hand, and had to suggest something longer than `match`. ## Solution **`match` on a union of string literals** (`@evobug_com/safe-ts-std/enum`), checked as for an enum: - `match(command, { open: () => …, urls: () => …, help: () => … })`. A missing member or a misspelled one doesn't compile. - `_` gets the members left, as strings. On an `Option` of a union, the `undefined` handler or `_` covers the missing value. - A plain `string` doesn't compile. The error message names the problem: `match needs an enum or a union of string literals, not \`string\``. - **Numbers are not supported.** Handler keys are object keys, so a numeric code would need `"0"`-style keys or computed `[Phase.WALK]` keys. The rewrite can't handle computed keys, and either form loses the names. The docs point numeric code sets at `switch` + `unreachable` or a `Record<Code, T>` table. Types: `match` keeps its single signature, as its comments ask. - The handler keys are `Extract<E, Tagged>["tag"] | Extract<E, string>`. A conditional `KeyOf` stopped TypeScript from inferring the handlers' keys, and with them every handler's parameter type. I bisected this to `MatchKeys`. - The plain-`string` rejection is a separate `ClosedSet<V>` term on the parameter, for the same reason. Runtime: `match` reads `typeof value === "string" ? value : value.tag`, and now looks only at the handler object's **own** properties. A member like `"toString"` with no handler of its own must reach `_`, not `Object.prototype.toString`. **The build** turns it into `switch (value)`. The transform has no types, so the whole-program pass decides for each `match` (`json::value::match_on`). `shape.rs` records the shape of the matched value, including the value inside a dev check's wrap. - **An enum** (or `Open<K>`): `switch` on `.tag`, as before. - **A union of string literals:** `switch` on the value. - **Type not found, in TypeScript:** the call stays a runtime `match`, and `safe-ts explain` says why. The emitted TypeScript must type-check, and only a `switch` on `.tag` narrows the value for the handlers. One exception: a handler that destructures its parameter (`({ radius }) =>`) is on an object, so that call is lowered on `.tag`. - **Type not found, in JavaScript:** `switch (typeof v === "string" ? v : v.tag)`. To keep enum matches lowered: - A declared type that mentions an outer type parameter is now read with that parameter as `unknown` (`Tree<T>` is a `Tree<unknown>`). Before, the whole type was unknown. A type that is a bare `T`, or contains a mapped or conditional type, stays unknown as before. - Measured over the repo's `match` calls (examples, std tests, benches, Vue/React packages): 47 enum matches lowered on `.tag` before and after. 9 new union matches are lowered on the value. 1 numeric match is left as a call, and that one doesn't compile anyway. The **dev check** accepts strings, and names the string with no handler (`match got "close", which has no handler here (handled: open, urls)`). The rule messages from #91 now suggest `match` for a union of strings: `exhaustive-dispatch`, `exhaustive-switch` and `string-dispatch`. ## Tests - `cargo nextest run --workspace`: 283 passed. - New transform tests: - the exact output for a union and for an `Option` of one; - an unknown type stays a call, and the destructuring hint; - `explain`; - one that runs the source and the rewrite in Node and compares the output. - Existing transform tests that matched on undeclared types now declare them (`TYPES`). - `npm run test:std`: 369 passed. Covers runtime and rewritten string matches, the `toString` member, and the dev check. - `packages/std/test/enum.check.ts` covers the types: exhaustive, `_`, `undefined`, misspelled members, plain `string` and numbers rejected. `tsc -p packages/std` passes, and so does `npm run typecheck:emit` (the emitted output type-checks). - `node scripts/docs-typecheck.mjs`: 620 examples compile. The docs examples test passes. - `npm run bench:check`: passes. `match / switch, through the transform` is 0.98x (limit 1.92x). ## Docs - `guide/enums.md`: a new section, "Matching a union of strings", plus the tip, the dispatch section and the TypeScript `enum` section. - `exhaustive-dispatch.md` gets a union example. `string-dispatch.md`'s accepted example now uses `match`. `exhaustive-switch.md` mentions `match`. - `json.md`'s `czech` example uses `match` with `_`. - `dev-checks.md`, `transforms.md`, the skill's `patterns-core.md` and `tool-gaps.md`, and CHANGELOG. ## Left out - **Vue/React `<Match>`** still takes an enum only (the docs say so). Use `match` in a `computed` instead. - **A string union with the literal `"undefined"` or `"_"` as a member** collides with those handler keys. It's not handled; I expect it to be rare. - **`must-use-result` reports a discarded `match(...)` statement** (it reads `match`'s return-type alias, which is named `Result`). This was already the case for enums. I wrote the docs example as `return match(...)` and didn't change the rule. Created with Claude Opus 5.5 in Claude Code.
match on a union of string literals
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m42s
ed33fa2819
`match(command, { open: ..., urls: ... })` with `type Command = "open" | "urls" | "help"`,
checked like an enum: a handler per member, `_` for the rest (the strings left), an
`undefined` handler for an Option of one. A plain `string` doesn't compile; numbers aren't
matched (switch + unreachable, or a Record table).

- std: one signature still; the keys are `Extract`s (a conditional key type stopped
  TypeScript inferring the handlers), the plain-string rejection a separate term. The
  runtime reads the string itself, and only the handlers' own properties.
- transform: the whole-program pass says what each match is given (json::value::match_on,
  from the value's shape): an enum keeps the switch on `.tag`, a union of strings gets
  `switch (value)`; a type it can't find stays a call in TypeScript (explain says so) and
  reads either in JavaScript. A handler that destructures its value says enum.
- shape.rs reads a declared type mentioning an outer type parameter with it `unknown`
  (`Tree<T>`), so a match on a generic enum is still lowered.
- dev check accepts strings and names the one without a handler.
- rule messages (exhaustive-dispatch, exhaustive-switch, string-dispatch) suggest `match`
  for a union of strings; docs, skill and CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee changed target branch from closed-set-dispatch to main 2026-11-20 16:41:03 +01:00
sionzee force-pushed closed-set-dispatch-match from ed33fa2819
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m42s
to e98aea0c30
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m21s
2026-11-20 16:44:42 +01:00
Compare
sionzee deleted branch closed-set-dispatch-match 2026-11-20 16:44:47 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!97
No description provided.