Discriminating Unions

When you have mutliple types and you want to create a type that is the union of them, you can give them all a shared property where reach type has its own type for it and then discriminate based on that type.

You could do:

Or use Discriminating Unions, add a literal type to the interfaces which are part of the union. Then we can check that individual property to see what type represents the value:


This only works because all of the members of the Union have a similar property, but the property doesn't have to be a literal type. As long as the type is different for each of the members, we can check against it. For example, TypeScript's type checker is intelligent enough to determine the type when we use a truthiness check on a member that could be null.

Copyright 2023 © Borja Leiva

Made within London