type narrowing in live queries
Hey all! I've got a series of events which I'd like to filter out (and type narrow) in order to produce aggregates. Here's what I have so far:
The problem I have here is that
pingEventCollection ends up with the full EventSchema type instead of being properly narrowed to just PingAddedV1Schema. How can I get this type narrowing?8 Replies
rising-crimson•2mo ago
you can set the schema on the live query collection
rival-black•2mo ago
I think it’s the same stuff as described here? https://github.com/TanStack/db/issues/413
schema won’t fix the issue, because I’d like to have few different objects as union in one collection and filter it. Same as I’d do with standard JS array, where filter narrows the result
GitHub
Working with discriminated unions inside of collection causes TS tr...
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 MessagePar...
rival-black•2mo ago
Oh, nvm I see - setting schema at derived collection level. That sounds smart. Will it actually parse the results?
rising-crimson•2mo ago
schemas only parse/validate optimistic mutations — so adding a schema or generic type is just to set the type when using the data
rival-black•2mo ago
Ah, right, we talked about it briefly before 😄 That's a bit sad, because
where can easily don't match the schema, that's why normal narrowing is really nicerising-crimson•2mo ago
Yeah that would be neat! I'm not sure how to do it so if you want to dig into figure this out that'd be great!
rival-black•2mo ago
Yeah, started thinking about this already :D
rising-crimsonOP•2mo ago
Yeah, seems to be the same problem. I’m using Zod, but that’s essentially the only difference.
uh, this may be a terrible idea, but… we already have schemas. What if there was a
.narrow function (name to be bikeshedded) that took a schema and simply validated values to remove non-matches? There are probably some typescript tricks we could do to ensure that SubSchema extends Schema etc
the reason I think it might be a terrible idea is that it would have a runtime cost. As an alternative to .where, though, maybe it's acceptable?