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 ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.