Unions and Indexing 10 exercises

Union Terminology Examples

The answer is that A is a discriminated union.

type A =
| {
type: "a"
a: string
| {
type: "b"
b: string
| {
type: "c"
c: string

B is a union, but not a discriminated union.

type B = "a" | "b" | "c"

C is an

Loading solution


0:00 The answer here is that A is a discriminated union, B is a union, and C is an enum. I'm going to touch enums later. Let's look at unions and discriminated unions. Now, the difference here is, is that when you have a discriminated union, you have a common key or a common aspect to that object, or whatever you're representing here, that is the discriminator.

0:26 It lets us, if we say, "Get union," imagine this function, and we have a result, which is of type A. Now, this result, we can say, "If result.type equals A, then we can access this little bit of it." Whereas, if we try to just say, "Result.A here," then TypeScript is actually going to yell at us because it doesn't exist on this discriminator, for instance.

0:50 This lets us do really clever things here. We can say, "Results.A," for instance. These don't have to be the same as the discriminated union. These can be whatever, something, and who cares, down here. If I try to access, or I type it to be C, so it understands that we're inside this member, then just inside this closure, then we're going to get access to who cares here. Pretty cool.

1:14 A union is different because a union, it doesn't really carry any properties along with it. It just is itself. We would check if it's A, then do something. Check if it's B, and check if it's C. Discriminated unions are super-duper useful as a type because they can represent different props in React, different weight, like methods of behavior for your function.

1:35 They're really, really cool. I wanted to introduce them here so that they're in your mind for later.