Type Transformations Workshop (9 exercises)

Union Terminology Examples

The answer is that A is a discriminated union.

B is a union, but not a discriminated union.

C is an enum.

We’ll talk more about enums later. For now, let’s look at the differences between a discriminated union and a regular union.

Discriminated Unions vs. Unions

A discriminated union has something in common with whatever you’re representing. For example, if you’re working with an object you would have a common key.

This common aspect is called the discriminator.

Take this getUnion function that takes in a result of type A, for example:

Inside of this function, we can check if result.type == 'a'.

However, if we try to access result.a, TypeScript will yell at us since the a key does not exist on b or c from our exercise:

But we know members with a type of "a" will have an a property, so we can safely access it.

Unions, on the other hand, don’t carry any properties along with them.

As seen in our exercise example, we are able to check if something is "a" then do something.

Both types are useful, and we’ll see them throughout the workshop.


[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.