Learning TypeScript 2.x
上QQ阅读APP看书,第一时间看更新

Union types

TypeScript allows you to declare union types:

let path: string[]|string;
path = "/temp/log.xml";
path = ["/temp/log.xml", "/temp/errors.xml"];
path = 1; // Error

In the preceding example, we have declared a variable named path that can contain a single path (string) or a collection of paths (array of strings). In the example, we have also set the value of the variable. We assigned a string and an array of strings without errors; however, when we attempted to assign a numeric value, we got a compilation error, because the union type didn't declare a number as one of the valid types of the variable.

Union types are used to declare a variable that can store a value of two or more types. Only the properties available in all the types present in the intersection type are considered valid:

We can appreciate this behavior in the following example:

interface Supplier {
orderItems(): void; getAddress(): void; } interface Customer { sellItems(): void; getAddress(): void; } declare let person: Supplier | Customer; person.getAddress(); // OK person.orderItems(); // Error person.sellItems(); // Error