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
:
type UserID = string | number;
let id: UserID;
id = 'test1'; // OK
id = 2000000; // OK
id = true; // Error
id = [1, 2]; // Error
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:
type Month =
| 'January'
| 'February'
| 'March'
| 'April'
| 'May'
| 'June'
| 'July'
| 'August'
| 'September'
| 'October'
| 'November'
| 'December';
const birthdayMonth: Month = 'November'; // OK
const summerMonth: Month = 'July'; // OK
const winterMonth: Month = 'Decemb'; // Error
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:
const winterMonth: Month = 'December'; // OK
When using unions on object types, we are able to express that an object may have one of several shapes:
type Student = {
name: string;
age: number;
major: string;
};
type Professor = {
name: string;
age: number;
classes: string[];
};
type SchoolMember = Student | Professor;
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:
let member: SchoolMember;
member = {
name: 'Alec',
age: 53,
classes: ['calculus 1', 'machine learning'],
}; // OK
member = {
name: 'Lisa',
age: 32,
major: 'Computer Science',
}; // OK
This page is a preview of Beginners Guide to TypeScript