July 2017
Intermediate to advanced
384 pages
8h 23m
English
A union type describes a value that can be one of many types. The vertical bar | is used as separator for each type the value can have. For instance, number | string is the type of a value that can be a number or string. For such values, we can only access members that are common to all types in the union. The following code works because the length property exists on both strings and arrays:
var value: string | string[] = 'some';let length = value.length;
The next code snippet gives an error because the model property does not exist on the Bike type:
interface Bike { gears: number;}interface Car { gears: number; model: string;}var transport: Bike | Car = {gears: 1};transport.model = "Audi"; // compiler error ...Read now
Unlock full access