Transcript from the "Unions vs. Interfaces" Lesson
>> Scott Moss: How do you know when to use unions versus interfaces? You can actually use them both in the same context. But the way they were designed is that an interface is used for types that are very common with maybe a couple different fields that are different. Whereas a union was designed to nothing is the same, none of these types have any of the same fields.
[00:00:26] That's the expectation, but because of the nature of how you use them, they can be used exactly the same. They have the same restrictions, you got to us a inlined fragment to access them, you only can use custom types to compose them. So it's really up to you, you'll be using interfaces a lot, I'll tell you that.
[00:00:45] Unions, not so much, interfaces quite a lot.
>> Speaker 2: Yeah, it seems like unions kind of take away some of that expected type safety from the front end of the response. Cuz then you'd have to, I'm just kind of imagining that I wanna process this array of known, but unknown objects into some view.
>> Scott Moss: Yeah you do lose some type safety there because it's like especially if the types are so different from each other, just completely different. Now you're just like I have no idea what's going on here. So, yeah you got to be careful with that. Whereas the interface is like, there are some common things here.
[00:01:22] But that comes down to just data modeling and how you want to model that. So, yeah, I totally agree. What I would do in that case is I would avoid a union across huge differences in types. And what I would do, is instead, I would make another type that would take those different types from the database and compose them with some similar fields.
[00:01:44] I would just change them around and virtualize them to where that there were some similarities and then use an interface. That way I'm not like, I have no idea what's going on here. You on the front end checking properties, if this, if this, if this, yeah that's horrible.