match on a union of string literals #97
Loading…
Reference in a new issue
No description provided.
Delete branch "closed-set-dispatch-match"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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 tomain.Problem
The enums guide recommends a union of strings (
"red" | "green") for plain names, butmatchtook only anEnum. For a union, the only exhaustive forms wereswitch+unreachableand aRecordtable. The rules in #91 found these unions dispatched by hand, and had to suggest something longer thanmatch.Solution
matchon 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 anOptionof a union, theundefinedhandler or_covers the missing value.stringdoesn't compile. The error message names the problem:match needs an enum or a union of string literals, not \string``."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 atswitch+unreachableor aRecord<Code, T>table.Types:
matchkeeps its single signature, as its comments ask.Extract<E, Tagged>["tag"] | Extract<E, string>. A conditionalKeyOfstopped TypeScript from inferring the handlers' keys, and with them every handler's parameter type. I bisected this toMatchKeys.stringrejection is a separateClosedSet<V>term on the parameter, for the same reason.Runtime:
matchreadstypeof 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_, notObject.prototype.toString.The build turns it into
switch (value). The transform has no types, so the whole-program pass decides for eachmatch(json::value::match_on).shape.rsrecords the shape of the matched value, including the value inside a dev check's wrap.Open<K>):switchon.tag, as before.switchon the value.match, andsafe-ts explainsays why. The emitted TypeScript must type-check, and only aswitchon.tagnarrows 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.switch (typeof v === "string" ? v : v.tag).To keep enum matches lowered:
unknown(Tree<T>is aTree<unknown>). Before, the whole type was unknown. A type that is a bareT, or contains a mapped or conditional type, stays unknown as before.matchcalls (examples, std tests, benches, Vue/React packages): 47 enum matches lowered on.tagbefore 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
matchfor a union of strings:exhaustive-dispatch,exhaustive-switchandstring-dispatch.Tests
cargo nextest run --workspace: 283 passed.Optionof one;explain;TYPES).npm run test:std: 369 passed. Covers runtime and rewritten string matches, thetoStringmember, and the dev check.packages/std/test/enum.check.tscovers the types: exhaustive,_,undefined, misspelled members, plainstringand numbers rejected.tsc -p packages/stdpasses, and so doesnpm 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 transformis 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 TypeScriptenumsection.exhaustive-dispatch.mdgets a union example.string-dispatch.md's accepted example now usesmatch.exhaustive-switch.mdmentionsmatch.json.md'sczechexample usesmatchwith_.dev-checks.md,transforms.md, the skill'spatterns-core.mdandtool-gaps.md, and CHANGELOG.Left out
<Match>still takes an enum only (the docs say so). Usematchin acomputedinstead."undefined"or"_"as a member collides with those handler keys. It's not handled; I expect it to be rare.must-use-resultreports a discardedmatch(...)statement (it readsmatch's return-type alias, which is namedResult). This was already the case for enums. I wrote the docs example asreturn match(...)and didn't change the rule.Created with Claude Opus 5.5 in Claude Code.
`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]>ed33fa2819e98aea0c30