Let's start writing some TypeScript!
In the following sections, we will take a look at different snippets showing some of the features of TypeScript. In order to be able to run the snippets and play with them yourself, you'll need to install the TypeScript compiler on your computer. Let's take a look at how to do this.
TypeScript is best installed using Node Package Manager (npm). I'd recommend that you use npm's version 3.0.0 or newer. If you don't have node.js and npm installed already, you can visit https://nodejs.org and follow the instructions there.
Once you have npm installed and running, verify that you have the latest version by opening your terminal window and running the following command:
$ npm -v
Use the following command in order to install TypeScript 2.1.0 or newer:
$ npm install -g typescript@^2.1.0
The preceding command will install the TypeScript compiler and add its executable (tsc
) as global.
In order to verify that everything works properly, you can use the following command:
$ tsc -v
Version 2.1.1
The output should be similar to the preceding one, though possibly with a different version.
Now, let's compile our first TypeScript program! Create a file called hello.ts
and enter the following content:
// ch3/hello-world/hello-world.ts console.log('Hello world!');
Since we've already installed the TypeScript compiler, you should have a global executable command called tsc
. You can use it in order to compile the file:
$ tsc hello.ts
Now, you should see the file hello.js
in the same directory where hello.ts
is. hello.js
is the output of the TypeScript compiler; it contains the JavaScript equivalent to the TypeScript you wrote. You can run this file using the following command:
$ node hello.js
Now, you'll see the string Hello world! printed on the screen. In order to combine the process of compiling and running the program, you can use the ts-node
package:
$ npm install -g ts-node
Now you can run:
$ ts-node hello.ts
You should see the same result, but without the ts-node
file stored on the disk.
You can find the code for this book at https://github.com/mgechev/getting-started-with-angular. Most code snippets have a comment as the first line, which shows where you can find the complete example in the directory structure of the samples repository. Note that the paths are relative to the app
directory.