TypeScript helps bring your JavaScript projects sanity by providing strong type checking and all the latest and greatest ECMAScript features. This article will show you how to quickly and easily add TypeScript to your project, old or new.
Start Coding in TypeScript Quickly and Easily
Without wasting any time, let's install TypeScript. Provided you have your favorite text editor as well as NodeJS and NPM (Node Package Manager) handy, you are ready to install TypeScript.
Step One: Find Your Project Folder
Within your favorite command window, navigate to your project directory.
cd my-javascript-project
Step Two: Install TypeScript
Once you are in your project's directory, run the following command to install the latest stable version of TypeScript.
npm install typescript
Final Step: Compile!
Now that we have installed TypeScript, we just need to create our first TypeScript file and convert it into JavaScript. To do this we must run tsc
against our newly created TypeScript file.
Here I will create app.ts
. My app requires that I sum all the elements within an array of numbers, so I will create a class called MyApp
that contains a method, add
, that takes in as a parameter an array of numbers, and returns a single value that represents the sum of all its number elements.
export class MyApp {
public add = (numbersToAdd: number[]): number => {
return numbersToAdd.reduce((a, b) => {
return a + b;
}, 0);
}
}
Now, all we need to do is run the executable, tsc
, against our new file name. I will use the -t es5
option to target ECMAScript 5 in the event I want my JavaScript to work nicely in older browsers.
tsc -t es5 app.ts
And there we go! Here is our transpiled JavaScript file, app.js
.
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MyApp = /** @class */ (function () {
function MyApp() {
this.add = function (numbersToAdd) {
return numbersToAdd.reduce(function (a, b) {
return a + b;
}, 0);
};
}
return MyApp;
}());
exports.MyApp = MyApp;
Conclusion
This article by no means goes into great detail about all of the features TypeScript can provide for us, but I hope this proves to be useful to those seeking a quick reference or are simply looking to learn more about TypeScript.
Happy Coding!