Working with discriminated unions inside of collection causes TS troubles
Nobody has claimed this yet.
- Dominant language
- TypeScript
- Stars
- 3.9k
- Forks
- 266
- Avg merge
- 1d 4h
- Merged PRs (30d)
- 55
Description
Hello 👋
I'm building some small app with tanstack db and one things that bugs me is working with discriminated unions inside of collections. The app is AI chat, so for example I have MessagePart shape, which can be TextMessagePart, ReasoningMessagePart etc. Unfortunately, it's not properly narrowed in many places when using it.
I made a small reproduction, where you can see these issues, that's much easier then to describe it:
As an example I chosen a schema where discriminator is also TKey to showcase also the 2. issue, but it also doesn't work in cases where it's just one of the fields. In my app I have shape with 3 fields basically id, type, data and data is different based on type, I can't properly query this without typecasting/asserting atm
But for completeness:
- Can't discriminate union in either
.whereor.fn.where. It always result in the full model - Collection
TKeyis only inferred properly for few collection types, doesn't work e.g. with local storage or electric ones. They don't pass necessary generics getandupdatein cases whereTKeyis discriminator doesn't properly discriminate
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the reproduction in src/lib/collections.ts and trace the types used by .where and .fn.where for the discriminated MessagePart union. Then inspect collection implementations using local storage and Electric, along with get and update, to compare how TKey generics are passed. Done means discriminator-based narrowing works across these operations without type assertions and TKey is inferred correctly.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- database
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100