std: match() infers the union of its handlers' results #25
Loading…
Reference in a new issue
No description provided.
Delete branch "fix/std-match-inference"
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?
What
match()from@evobug/safe-ts-std/enumreturnedunknownwhenever nothing around the call gave it a result type. Examples:const x = match(...),computed(() => match(...)), a ReactuseMemo(() => match(...)).Why: the signature was
match<E, R>(value: E, handlers: Handlers<E, R>): R.Handlers<E, R>is a mapped type overE["tag"]. TypeScript can't list its properties whileEis still being inferred, so it never infersRfrom the handlers. This is true for plain arrows, destructuring arrows and mixes of both. With tsc 7.0.2, even{ A: () => 1, B: () => 2 }givesunknown. It looked like a problem with mixed arrows only because every existing test and doc example has a declared return type, and that is what suppliedR.Fix (
packages/std/src/enum.ts):H, constrained byHandlers<E, unknown>(orHandlersWithFallback<E, unknown>). Handlers are still contextually typed, so destructuring still sees the variant's fields, and a missing variant is still a compile error.MatchResult<H>: the union of what the handlers return, with_included.His inferred, the object literal no longer gets an excess-property check.OnlyKeysmaps unknown keys tonever, soCircel: ...next to_, or an extra variant, still fails.Ralso means_no longer has to "fit" the named handlers' type. It simply joins the union. If a declared return type doesn't fit, the error is at the call.The build-time rewrite (
matcher.rs,match→switch) doesn't read these types.npm run typecheckrunsenum.check.tsthroughsafe-ts emitand tsc, and both the rewritten and the original forms typecheck.Tests
packages/std/test/enum.check.tshas new type-level tests using an exactEqual<A, B>check:_,_onlyThe six positive cases failed before the fix (
unknown).Commands run:
tsc -pon every package and example tsconfig (std, std emit, safe-ts-vue, demo, demo emit): all passnpm run typecheck(with emit): passescargo nextest run: 104 passednpm run test:std: 130 passednpm run test:vite: passesnpm run test:docs: passesDocs
There are no workaround annotations for this on
main. The doc examples all have declared return types, and the Vuecomputed(() => match(...))examples just had anunknownresult nobody read. #19 (React section, not merged yet) has annotations added for this. They can be dropped once both are in.Uncertain
_'s parameter is still the whole enum, so_: ({ tag }) => tagadds every tag literal to the union, including handled ones.🤖 Generated with Claude Code