Using v.id() in a v.union()
I'm testing out something in my dev env, trying to improve how we handle the relation between a video and a call to action. I'm considering doing the following:
Old approach using a string
New approach using a union
The new approach not only allows me to use the type for doing some smart dynamic rendering of a component based on the type in the frontend, and the id with the union types of the different id's for a call to action, allows me to easily delete the id in the backend.
Is there any reasons not to do it this way. Before i migrate things to this new approach.
4 Replies
I would do it but make the Union one of objects:
Then typescript will give you the ID type when you match the string type, and you can add extra per-type fields later if you want
@oscklm make sense?
Interesting. But i’m not 100% sure I follow
For more context this is how im using the way i've done it currently.
Hmm. Do i understand correctly, that by the approach you recommend. That way i enforce that FunFact and the funFacts id will be paired together? and therefore can use the id field more conveniently?
Ahh i think it clicked
Yup, this would still work. Under the hood, if all the objects you have a union of have an
id
key, and they're all of the v.id
(Id
) type, then doing video.currentCallToAction.id
will have a type of the union of the id types. The benefit is if you do:
fact
will then have a type Doc<'funFacts'>
, not a union of all the types. This is called "narrowing" and the union of objects is called a "discriminated union" - where there's a field that can distinguish which of the subtypes it isOhh that’s super cool. Thanks for elaborating on this! I will have to read more up on the concepts you mention here