Install the TypeScript transpiler using npm:
$ npm install -g typescript
Then use tsc to manually compile a TypeScript source file into ES5:
$ tsc test.ts
$ node test.js
TypeScript is more demanding than ES6 and it expects instance properties to be declared:
class Pizza {
toppings: string[];
constructor(toppings: string[]) {
this.toppings = toppings;
}
}
Note that now that we’ve declared toppings to be an array of strings, TypeScript will enforce this. If we try to assign a number to it, we will get an error at compilation time.
If you want to have a property that can be set to a value of any type, however, you can still do this: just declare its type to be “any”:
class Pizza {
toppings: any;
//…
}
Typings
Astute readers might be wondering what happens when TypeScript programmers need to interface with JavaScript modules that have no type information. TypeScript recognizes files labelled *.d.ts as definition files. These files are meant to use TypeScript to describe interfaces presented by JavaScript libraries.
There are communities of people dedicated to creating typings for JavaScript projects. There is also a utility called typings (npm install –save-dev typings) that can be used to manage third party typings from a variety of sources. (Deprecated in TypeScript 2.0)
In TypeScript 2.0, users can get type files directly from @types through npm (for example, npm install –save @types/lodash will install lodash type file).
Linting
Many editors support the concept of “linting” – a grammar check for computer programs. Linting can be done in a programmer’s editor and/or through automation.
For TypeScript there is a package called tslint, (npm install –save-dev tslint) which can be plugged into many editors. tslint can also be configured with a tslint.json file.
Webpack can run tslint before it attempts to run tsc. This is done by installing tslint-loader (npm install –save-dev tslint-loader) which plugs into webpack like so:
// ... module: { preLoaders: [ { test: /\.ts$/, loader: 'tslint' } ], loaders: [ { test: /\.ts$/, loader: 'ts', exclude: /node_modules/ }, // ... ] // ... }