HTML and CSS Reference
In-Depth Information
Figure 19-8. Your first generated JavaScript file from TypeScript
You now have your module and class compiled into JavaScript. Note again that this JavaScript is fully readable.
If you ever find yourself no longer wanting to use TypeScript, you can simply take all the JavaScript files out and
use them without TypeScript or even tell the compiler to generate each TypeScript file separately.
Next, let's get this connected in your main.ts file. Replace “Hello TypeScript” with the following code:
window.onload = () => {
var canvas = <HTMLCanvasElement>document.getElementById('display');
var rogueTS = new rogue.Game(canvas);
};
You may recognize that you are setting up an onload call to get the canvas and create your RogueTS game. What
may look strange is how you actually set up this callback. The arrow notation => is how TypeScript binds a callback to
a generic method. The biggest advantage of this in TypeScript, which you will see later in the chapter, when you set
up your game loop (see the section “Drawing to Canvas”), is that the compiler will actually fix scoping in this generic
function for you. To pass the scope back to a generic method, you may have had, at some point, to do a scope hack
similar to this one:
var that = this;
TypeScript alleviates the need for this completely when you take advantage of the arrow notation. You will
continue to use this notation as you build out your game, so don't worry; you will get more hands-on time with it.
Note that you get a reference to the canvas via a normal document.getElementById call. What may look strange
is the addition of <HTMLCanvasElement> before it. This is called casting . Basically, because TypeScript sits on top of
JavaScript, which is an untyped language, when you make JavaScript calls, you will always get back a generic object.
You will have to type cast these objects to allow TypeScript to do its type checking correctly. You may also notice that
you don't set an explicit type to your canvas variable. The compiler is smart enough to infer the type of var by the
casting type. This can save you some time by not having to worry too much about adding types to each variable you
define locally in a method or function.
You also create a new reference to your game. If you have ever used the new constructor in any language,
including JavaScript, this should look very familiar to you. As you can see, you need to include the module name, plus
the class, so you call rogue.Game and pass in a reference to the canvas. If you go back to the page in your browser and
refresh, you should see the canvas element being traced out to the console, as shown in Figure 19-9 .
 
Search WWH ::




Custom Search