23.06.2015 Views

TypeScript Language Specification v1.5

TypeScript Language Specification v1.5

TypeScript Language Specification v1.5

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

In a contextually typed parenthesized expression, the contained expression is contextually typed<br />

by the same type.<br />

In a type assertion, the expression is contextually typed by the indicated type.<br />

In a || operator expression, if the expression is contextually typed, the operands are contextually<br />

typed by the same type. Otherwise, the right expression is contextually typed by the type of the<br />

left expression.<br />

In a contextually typed conditional operator expression, the operands are contextually typed by<br />

the same type.<br />

In an assignment expression, the right hand expression is contextually typed by the type of the<br />

left hand expression.<br />

In the following example<br />

interface EventObject {<br />

x: number;<br />

y: number;<br />

}<br />

interface EventHandlers {<br />

mousedown?: (event: EventObject) => void;<br />

mouseup?: (event: EventObject) => void;<br />

mousemove?: (event: EventObject) => void;<br />

}<br />

function setEventHandlers(handlers: EventHandlers) { ... }<br />

setEventHandlers({<br />

mousedown: e => { startTracking(e.x, e.y); },<br />

mouseup: e => { endTracking(); }<br />

});<br />

the object literal passed to 'setEventHandlers' is contextually typed to the 'EventHandlers' type. This<br />

causes the two property assignments to be contextually typed to the unnamed function type '(event:<br />

EventObject) => void', which in turn causes the 'e' parameters in the arrow function expressions to<br />

automatically be typed as 'EventObject'.<br />

4.20 Type Guards<br />

Type guards are particular expression patterns involving the 'typeof' and 'instanceof' operators that cause<br />

the types of variables or parameters to be narrowed to more specific types. For example, in the code<br />

below, knowledge of the static type of 'x' in combination with a 'typeof' check makes it safe to narrow the<br />

type of 'x' to string in the first branch of the 'if' statement and number in the second branch of the 'if'<br />

statement.<br />

81

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

Saved successfully!

Ooh no, something went wrong!