
Putting everything together
Now that we have learned how to use the basic TypeScript building blocks individually, let's take a look at a final example in which we will use modules, classes, functions, and type annotations for each of these elements:
namespace geometry_demo { export interface Vector2DInterface { toArray(callback: (x: number[]) => void): void; length(): number; normalize(): void; } export class Vector2D implements Vector2DInterface { private _x: number; private _y: number; constructor(x: number, y: number) { this._x = x; this._y = y; } public toArray(callback: (x: number[]) => void): void { callback([this._x, this._y]); } public length(): number { return Math.sqrt( this._x * this._x + this._y * this._y ); } public normalize() { let len = 1 / this.length(); this._x *= len; this._y *= len; } } }
The preceding example is just a small portion of a basic 3D engine written in JavaScript. In 3D engines, there are a lot of mathematical calculations involving matrices and vectors. As you can see, we have defined a module Geometry that will contain some entities; to keep the example simple, we have only added the class Vector2D. This class stores two coordinates (x and y) in 2D space and performs some operations on the coordinates. One of the most widely used operations in vectors is normalization, which is one of the methods in our Vector2D class.
3D engines are complex software solutions, and as a developer, you are much more likely to use a third-party 3D engine than create your own. For this reason, it is important to understand that TypeScript will not only help you develop large-scale applications but also interact with complex libraries.
In the following code snippet, we will use the module declared earlier to create a Vector2D instance:
let vector: geometry_demo.Vector2DInterface = new geometry_demo.Vector2D(2,3); vector.normalize(); vector.toArray(function(vectorAsArray: number[]){ console.log(`x: ${vectorAsArray[0]}, y: ${vectorAsArray[1]}`); });
The type-checking and IntelliSense features will help us create a Vector2D instance, normalize its value, and convert it into an array to finally show its value on the screen with ease:
