Why choose TypeScript?

Posted on - Last Modified on

Typescript is a superset of JavaScript, developed by Anders Hejlsberg (the developer of Turbo Pascal, Delphi and C#). As the name of the language suggests, Typescript is a type-aware version of JavaScript. The programming language is open sourced on GitHub and is supported by Microsoft.

Installing the Typescript Compiler

The easiest way to install the typescript compiler is through npm by running:

greg@earth:~$ sudo npm install -g typescript

After the installation, typing tsc in your console will result in the following output:

typescript tsc output

The typescript files have a .ts extension. It is important to note that existing JavaScript code is accepted by the TypeScript compiler and mixing the TypeScript and JavaScript code won't generate errors (of course, it's still not a good practice to do that). The TypeScript compiler outputs standard JavaScript code by applying coding best practices that you may be familiar with from the JavaScript community.

Because of the mentioned advantages, using TypeScript does not involve any real risk. In case you decide that TypeScript is not a good option for you or your team, you can take the source code emitted by the TypeScript compiler, use that in the project and continue the development using JavaScript.

Types and Classes in TypeScript

You can explore the types available in TypeScript using the following code:

interface IProject {
	name:string;
	owners:Array<string>;
	description:string;
	price:number;
	wasFinished:boolean;
	currency:any;
}

class Project implements IProject {

	public name:string;
	public owners:Array<string>;
	public description:string;
	public price:number;
	public wasFinished:boolean;
	public currency:any;

	constructor(name:string, description:string, price:number, currency:any) {
		this.name = name;
		this.description = description;
		this.price = price;
		this.currency = currency;
		this.wasFinished = false;

		this.owners = new Array<string>();
	}

	addOwner(ownerName:string): void {
		this.owners.push(ownerName);
	}

	myToString(): string {
		var result = "Project Name:" + this.name
			+ ", Description:" + this.description
			+ ", Price:" + this.price
			+ ", Currency:" + this.currency
			+ ", WasFinished:" + this.wasFinished;

		return result;
	}
}

In the example above, I declared an interface (IProject). The class implementing the IProject interface has to have a name and description property of type string, an array of strings that stores the owners, a number for storing the price, an any type to store the currency (I could have used string, but wanted to illustrate the any type too) and a boolean (wasFinished), which shows if the project was finished or not. Thanks to the any type you can start using TypeScript in your project and rewrite the JS code step by step by adding the types for variables in iterations. The any type in TypeScript can basically store anything, the compiler will not give any errors if you assign a boolean or a string value to this type. The owners (array of strings) class member definition shows how you can use generic types in TypeScript for arrays.

The Project class implements the IProject interface. First I defined the properties, and all of these are public. When the TypeScript compiler parses the code, it will create properties for the generated JavaScript class (see below the generated JS code).

The constructor keyword can be used to define constructors for your classes. These can have parameters and there is no need to specify the return type. Besides the constructor, I also defined 2 functions: one for adding new owners to the project (storing in the owners array) and another one for representing the Project with a string.

The JavaScript code generated by the TypeScript compiler:

var Project = (function () {
    function Project(name, description, price, currency) {
        this.name = name;
        this.description = description;
        this.price = price;
        this.currency = currency;
        this.wasFinished = false;
        this.owners = new Array();
    }
    Project.prototype.addOwner = function (ownerName) {
        this.owners.push(ownerName);
    };
    Project.prototype.myToString = function () {
         var result = "Project Name:" + this.name + ", Description:" + this.description + ", Price:" + this.price + ", Currency:" + this.currency + ", WasFinished:" + this.wasFinished;
        return result;
    };
    return Project;
})(); 

The generated JavaScript code defines a new self-executing function. Inside, this function declares the Project function (and because of JavaScript closure), and the Project() function helps to create new instances of the Project object. The two methods, addOwner() and myToString(), are defined on the Prototype level of the Project object.

Using TypeScript classes

You can use TypeScript classes as any other JavaScript object:

/// <reference path="project.ts" />
var myProject = new Project("First Project", "Awesome Description of First Project", 100, "AUD");
var projectAsText = "Here is your Project:" + myProject.myToString();
console.log(projectAsText);
document.body.innerHTML = projectAsText;

The compiled JavaScript code:

/// <reference path="project.ts" />
var myProject = new Project("First Project", "Awesome Description of First Project", 100, "AUD");
var projectAsText = "Here is your Project:" + myProject.myToString();
console.log(projectAsText);
document.body.innerHTML = projectAsText;

The generated code does not have differences with the TypeScript code. Let's try to create a new Project object in TypeScript but let's also make some errors in code to see how the compiler reacts. For this code the compiler will give an error:

var myProject = new Project(1, {description:"project description"}, 100, "AUD");

The compiler output is:

sample.ts(3,29): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.

If I correct the error:

var myProject = new Project("First Project", {description:"project description"} , 100, "AUD");

I will still get an error message from the compiler:

sample.ts(3,46): error TS2345: Argument of type '{ description: string; }' is not assignable to parameter of type 'string'.

If you are interested in learning more about TypeScript, check out this video, where Andres Hejlsberg presents the ins and outs of the language, as well as the webpage of TypeScript.  

Posted 16 April, 2015

Greg Bogdan

Software Engineer, Blogger, Tech Enthusiast

I am a Software Engineer with over 7 years of experience in different domains(ERP, Financial Products and Alerting Systems). My main expertise is .NET, Java, Python and JavaScript. I like technical writing and have good experience in creating tutorials and how to technical articles. I am passionate about technology and I love what I do and I always intend to 100% fulfill the project which I am ...

Next Article

Jumpstart Your Freelance Copywriting Career