23.06.2015 Views

TypeScript Language Specification v1.5

TypeScript Language Specification v1.5

TypeScript Language Specification v1.5

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

3.4 Union Types<br />

Union types represent values that may have one of several disjoint representations. A value of a union<br />

type A | B is a value that is either of type A or type B. Union types are written using union type literals<br />

(section 3.7.6).<br />

A union type encompasses an unordered set of unrelated types (that is, types that aren't subtypes of each<br />

other). The following rules govern union types:<br />

A | B is equivalent to A if B is a subtype of A.<br />

A | B is equivalent to B | A.<br />

AB | C is equivalent to A | BC, where AB is A | B and BC is B | C.<br />

Union types are reduced to the smallest possible set of constituent types using these rules.<br />

Union types have the following subtype relationships:<br />

A union type U is a subtype of a type T if each type in U is a subtype of T.<br />

A type T is a subtype of a union type U if T is a subtype of any type in U.<br />

Similarly, union types have the following assignability relationships:<br />

A union type U is assignable to a type T if each type in U is assignable to T.<br />

A type T is assignable to a union type U if T is assignable to any type in U.<br />

The || and conditional operators (section 4.15.7 and 4.16) may produce values of union types, and array<br />

literals (section 4.6) may produce array values that have union types as their element types.<br />

Type guards (section 4.20) may be used to narrow a union type to a more specific type. In particular, type<br />

guards are useful for narrowing union type values to a non-union type values.<br />

In the example<br />

var x: string | number;<br />

var test: boolean;<br />

x = "hello";<br />

// Ok<br />

x = 42;<br />

// Ok<br />

x = test;<br />

// Error, boolean not assignable<br />

x = test ? 5 : "five"; // Ok<br />

x = test ? 0 : false; // Error, number | boolean not asssignable<br />

it is possible to assign 'x' a value of type string, number, or the union type string | number, but not any<br />

other type. To access a value in 'x', a type guard can be used to first narrow the type of 'x' to either string<br />

or number:<br />

var n = typeof x === "string" ? x.length : x; // Type of n is number<br />

30

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!