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 />

Declaration Spaces<br />

There are two declaration spaces in TypeScript: The variable declaration space and the type declaration space. These<br />

concepts are explored below.<br />

Type Declaration Space<br />

The type declaration space contains stuff that can be used as a type annotation. E.g the following are a few type<br />

declarations:<br />

class Foo { }<br />

interface Bar { }<br />

type Bas = {}<br />

This means that you can use Foo , Bar , Bas etc. as a type annotation. E.g.:<br />

var foo: Foo;<br />

var bar: Bar;<br />

var bas: Bas;<br />

Notice that even though you have interface Bar , you can't use it as a variable because it doesn't contribute to the variable<br />

declaration space. This is shown below:<br />

interface Bar {};<br />

var bar = Bar; // ERROR: "cannot find name 'Bar'"<br />

The reason why it says cannot find name is because the name Bar is not defined in the variable declaration space. That<br />

brings us to the next topic "Variable Declaration Space".<br />

Variable Declaration Space<br />

The variable declaration space contains stuff that you can use as a variable. We saw that having class Foo contributes a<br />

type Foo to the type declaration space. Guess what?, it also contributes a variable Foo to the variable declaration space<br />

as shown below:<br />

class Foo { }<br />

var someVar = Foo;<br />

var someOtherVar = 123;<br />

This is great as sometimes you want to pass classes around as variables. Remember that<br />

We couldn't use something like an interface that is only in the type declaration space as a variable.<br />

Similarly something that you declare with var , is only in the variable declaration space and cannot be used as a type<br />

annotation:<br />

var foo = 123;<br />

var bar: foo; // ERROR: "cannot find name 'foo'"<br />

Declaration Spaces<br />

40

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

Saved successfully!

Ooh no, something went wrong!