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.

function processValue(value: number | (() => number)) {<br />

var x = typeof value !== "number" ? value() : value;<br />

// Process number in x<br />

}<br />

the value parameter has type () => number in the first conditional expression and type number in the<br />

second conditional expression, and the inferred type of x is number.<br />

In the example<br />

function f(x: string | number | boolean) {<br />

if (typeof x === "string" || typeof x === "number") {<br />

var y = x; // Type of y is string | number<br />

}<br />

else {<br />

var z = x; // Type of z is boolean<br />

}<br />

}<br />

the type of x is string | number | boolean in the left operand of the || operator, number | boolean in<br />

the right operand of the || operator, string | number in the first branch of the if statement, and boolean<br />

in the second branch of the if statement.<br />

In the example<br />

class C {<br />

data: string | string[];<br />

getData() {<br />

var data = this.data;<br />

return typeof data === "string" ? data : data.join(" ");<br />

}<br />

}<br />

the type of the data variable is string in the first conditional expression and string[] in the second<br />

conditional expression, and the inferred type of getData is string. Note that the data property must be<br />

copied to a local variable for the type guard to have an effect.<br />

In the example<br />

class NamedItem {<br />

name: string;<br />

}<br />

function getName(obj: Object) {<br />

return obj instanceof NamedItem ? obj.name : "unknown";<br />

}<br />

84

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

Saved successfully!

Ooh no, something went wrong!