11.09.2015 Views

Typescript Deep Dive by Basarat Ali Syed

Typescript Deep Dive by Basarat Ali Syed

Typescript Deep Dive by Basarat Ali Syed

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.

TypeScript <strong>Deep</strong> <strong>Dive</strong><br />

Type Assertion<br />

TypeScript allows you to override its inferred and analyzed view of types any way you want to. This is done <strong>by</strong> a<br />

mechanism called "type assertion". TypeScript's type assertion are purely you telling the compiler that you know about the<br />

types better than it does, and that it should not second guess you.<br />

A common use case for type assertion is when you are porting over code from JavaScript to TypeScript. For example<br />

consider the following pattern:<br />

var foo = {};<br />

foo.bar = 123; // error : property 'bar' does not exist on `{}`<br />

foo.bas = 'hello'; // error : property 'bas' does not exist on `{}`<br />

Here the code errors because the inferred type of foo is {} i.e. an object with zero properties. Therefore you are not<br />

allowed to add bar or bas to it. You can fix this simply <strong>by</strong> a type assertion as Foo :<br />

interface Foo {<br />

bar: number;<br />

bas: string;<br />

}<br />

var foo = {} as Foo;<br />

foo.bar = 123;<br />

foo.bas = 'hello';<br />

as foo vs. <br />

Originally the syntax that was added was . This is demonstrated below:<br />

var foo: any;<br />

var bar = foo; // bar is now of type "string"<br />

However there is an ambiguity in the language grammar when using style assertions in JSX:<br />

var foo = bar;<br />

<br />

Therefore it is now recommended that you just use as foo for consistency.<br />

Type Assertion vs. Casting<br />

The reason why it's not called "type casting" is that casting generally implies some sort of runtime support. However type<br />

assertions are purely a compile time construct and a way for you to provide hints to the compiler on how you want your<br />

code to be analyzed.<br />

Fork me on github<br />

Type Assertion<br />

65

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

Saved successfully!

Ooh no, something went wrong!