Union Types, Discriminated Unions, and Type Guards

Union Types, Discriminated Unions, and Type Guards#

Union Types Denote "or"#

Union types allow us to represent types that are one among a set of types.

We use the | character to denote an "OR" relationship between two or more types. In the example below, we state that a UserID may be type string or number:

When unions are applied over primitives and literals, the union is exclusive, meaning the value being assigned to the union type cannot be two primitives or two literals at the same time. This is intuitive as a value cannot be both a string and a number, for example.

When we need a union over multiple types, we can split the union type into multiple lines, with each line starting with the | character (including the first line). In the example below, we declare type Month as a union of twelve string literal types:

We get an error for Decemb as this value is not assignable to any of the string literals in the Month union type. Fixing the typo resolves the error:

When using unions on object types, we are able to express that an object may have one of several shapes:

Unlike unions over primitives, unions over objects are inclusive, meaning an object may match multiple types in the union. In our example above, a SchoolMember may have either properties from Student, properties from Professor, or properties from both Student and Professor.

SchoolMember is assignable to the types below:


This page is a preview of Beginners Guide to TypeScript

No discussions yet