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.

o when false, removes the primitive type from the type of x.<br />

A type guard of the form typeof x === s, where s is a string literal with any value but 'string',<br />

'number', or 'boolean',<br />

o<br />

when true, if x is a union type, removes from the type of x all constituent types that are<br />

subtypes of the string, number, or boolean primitive type, or<br />

o when false, has no effect on the type of x.<br />

A type guard of the form typeof x !== s, where s is a string literal,<br />

o<br />

o<br />

when true, narrows the type of x by typeof x === s when false, or<br />

when false, narrows the type of x by typeof x === s when true.<br />

A type guard of the form !expr<br />

o<br />

o<br />

when true, narrows the type of x by expr when false, or<br />

when false, narrows the type of x by expr when true.<br />

A type guard of the form expr1 && expr2<br />

o<br />

when true, narrows the type of x by expr 1 when true and then by expr 2 when true, or<br />

o when false, narrows the type of x to T 1 | T 2 , where T 1 is the type of x narrowed by expr 1<br />

when false, and T 2 is the type of x narrowed by expr 1 when true and then by expr 2 when<br />

false.<br />

A type guard of the form expr1 || expr2<br />

o when true, narrows the type of x to T 1 | T 2 , where T 1 is the type of x narrowed by expr 1<br />

when true, and T 2 is the type of x narrowed by expr 1 when false and then by expr 2 when<br />

true, or<br />

o when false, narrows the type of x by expr 1 when false and then by expr 2 when false.<br />

A type guard of any other form has no effect on the type of x.<br />

In the rules above, when a narrowing operation would remove all constituent types from a union type, the<br />

operation has no effect on the union type.<br />

Note that type guards affect types of variables and parameters only and have no effect on members of<br />

objects such as properties. Also note that it is possible to defeat a type guard by calling a function that<br />

changes the type of the guarded variable.<br />

In the example<br />

function isLongString(obj: any) {<br />

return typeof obj === "string" && obj.length > 100;<br />

}<br />

the obj parameter has type string in the right operand of the && operator.<br />

In the example<br />

83

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

Saved successfully!

Ooh no, something went wrong!