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
cje
cje•2y ago
Types don’t exist at runtime
zenith
zenithOP•2y ago
Ok, interesting. I'll have to rethink this.
Vincent Udén
Vincent Udén•2y ago
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
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Vincent Udén
Vincent Udén•2y ago
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
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Vincent Udén
Vincent Udén•2y ago
No worries!
oldben
oldben•2y ago
if you have a union type then the 'in' operator is your friend for doing this:
interface Square { corners: number }
interface Circle { radius: number }
type Shape = Square | Circle
const whichShape = (shape: Shape) => {
if ('radius' in shape) {
// ... handle circle
}
}
interface Square { corners: number }
interface Circle { radius: number }
type Shape = Square | Circle
const whichShape = (shape: Shape) => {
if ('radius' in shape) {
// ... handle circle
}
}
Want results from more Discord servers?
Add your server