Conditional rendering on TS type
Hey everyone, I have a timeline that has multiple types coming over the wire in a list, and I need to render different ones depending on the type that it is. I seem to be getting an error on this, but not entirely sure how to correct. I tried using a comparison on typeof, but because that's comparing strings, it doesn't recognise that it's actually acting to guard the type.
the TimelineUpdate type just requires a WrittenUpdate and as it's type, and the WrittenUpdate type is imported from @prisma/client at the top of this file
Thanks 🙏
8 Replies
Types don’t exist at runtime
Ok, interesting. I'll have to rethink this.
Generally I'd say that using the type of a variable for control flow in the program is bad code smell. An options is having a broader update type with an enum on it which differentiates between the types of updates
Or if the types are full blown classes, just define a common interface for them
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
What? No. Pattern matching algebraic types is of course a staple of func. prog. So is overloading a function for different types. Using instance of isn't comparable at all imo
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
No worries!
if you have a union type then the 'in' operator is your friend for doing this: