Getting Started with TypeScript

Getting Started with TypeScript

Tutorial Details
  • Difficulty: Beginner
  • Completion Time: 30 Minutes

In late 2012, Microsoft introduced TypeScript, a typed superset for JavaScript that compiles into plain JavaScript. TypeScript focuses on providing useful tools for large scale applications by implementing features, such as classes, type annotations, inheritance, modules and much more! In this tutorial, we will get started with TypeScript, using simple bite-sized code examples, compiling them into JavaScript, and viewing the instant results in a browser.


Installing the Tools

TypeScript features are enforced only at compile-time.

You’ll set up your machine according to your specific platform and needs. Windows and Visual Studio users can simply download the Visual Studio Plugin. If you’re on Windows and don’t have Visual Studio, give Visual Studio Express for Web a try. The TypeScript experience in Visual Studio is currently superior to other code editors.

If you’re on a different platform (or don’t want to use Visual Studio), all you need is a text editor, a browser, and the TypeScript npm package to use TypeScript. Follow these installation instructions:

  1. Install Node Package Manager (npm)
    		$ curl http://npmjs.org/install.sh | sh
    		$ npm --version
    		1.1.70
    		
  2. Install the TypeScript npm package globally in the command line:
    		$ npm install -g typescript
    		$ npm view typescript version
    		npm http GET https://registry.npmjs.org/typescript
    		npm http 304 https://registry.npmjs.org/typescript
    		0.8.1-1
    		
  3. Any modern browser: Chrome is used for this tutorial
  4. Any text editor: Sublime Text is used for this tutorial
  5. Syntax highlighting plugin for text editors

That’s it; we are ready to make a simple “Hello World” application in TypeScript!


Hello World in TypeScript

TypeScript is a superset of Ecmascript 5 (ES5) and incorporates features proposed for ES6. Because of this, any JavaScript program is already a TypeScript program. The TypeScript compiler performs local file transformations on TypeScript programs. Hence, the final JavaScript output closely matches the TypeScript input.

First, we will create a basic index.html file and reference an external script file:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Learning TypeScript</title>
</head>
<body>

	<script src="hello.js"></script>

</body>
</html>

This is a simple “Hello World” application; so, let’s create a file named hello.ts. The *.ts extension designates a TypeScript file. Add the following code to hello.ts:

alert(‘hello world in TypeScript!’);

Next, open the command line interface, navigate to the folder containing hello.ts, and execute the TypeScript compiler with the following command:

tsc hello.ts

The tsc command is the TypeScript compiler, and it immediately generates a new file called hello.js. Our TypeScript application does not use any TypeScript-specific syntax, so we see the same exact JavaScript code in hello.js that we wrote in hello.ts.

Great! Now we can explore TypeScript's features and see how it can help us maintain and author large scale JavaScript applications.


Type Annotations

Type annotations are an optional feature, which allows us to check and express our intent in the programs we write. Let's create a simple area() function in a new TypeScript file, called type.ts

function area(shape: string, width: number, height: number) {
	var area = width * height;
	return "I'm a " + shape + " with an area of " + area + " cm squared.";
}

document.body.innerHTML = area("rectangle", 30, 15);

Next, change the script source in index.html to type.js and run the TypeScript compiler with tsc type.ts. Refresh the page in the browser, and you should see the following:

As shown in the previous code, the type annotations are expressed as part of the function parameters; they indicate what types of values you can pass to the function. For example, the shape parameter is designated as a string value, and width and height are numeric values.

Type annotations, and other TypeScript features, are enforced only at compile-time. If you pass any other types of values to these parameters, the compiler will give you a compile-time error. This behavior is extremely helpful while building large-scale applications. For example, let's purposely pass a string value for the width parameter:

function area(shape: string, width: number, height: number) {
	var area = width * height;
	return "I'm a " + shape + " with an area of " + area + " cm squared.";
}

document.body.innerHTML = area("rectangle", "width", 15); // wrong width type

We know this results in an undesirable outcome, and compiling the file alerts us to the problem with the following error:

$ tsc type.ts
type.ts(6,26): Supplied parameters do not match any signature of call target

Notice that despite this error, the compiler generated the type.js file. The error doesn't stop the TypeScript compiler from generating the corresponding JavaScript, but the compiler does warn us of potential issues. We intend width to be a number; passing anything else results in undesired behavior in our code. Other type annotations include bool or even any.


Interfaces

Let's expand our example to include an interface that further describes a shape as an object with an optional color property. Create a new file called interface.ts, and modify the script source in index.html to include interface.js. Type the following code into interface.ts:

interface Shape {
	name: string;
	width: number;
	height: number;
	color?: string;
}

function area(shape : Shape) {
	var area = shape.width * shape.height;
	return "I'm " + shape.name + " with area " + area + " cm squared";
}

console.log( area( {name: "rectangle", width: 30, height: 15} ) );
console.log( area( {name: "square", width: 30, height: 30, color: "blue"} ) );

Interfaces are names given to object types. Not only can we declare an interface, but we can also use it as a type annotation.

Compiling interface.js results in no errors. To evoke an error, let's append another line of code to interface.js with a shape that has no name property and view the result in the console of the browser. Append this line to interface.js:

console.log( area( {width: 30, height: 15} ) );

Now, compile the code with tsc interface.js. You'll receive an error, but don't worry about that right now. Refresh your browser and look at the console. You'll see something similar to the following screenshot:

Now let's look at the error. It is:

interface.ts(26,13): Supplied parameters do not match any signature of call target:
Could not apply type 'Shape' to argument 1, which is of type '{ width: number; height: number; }'

We see this error because the object passed to area() does not conform to the Shape interface; it needs a name property in order to do so.


Arrow Function Expressions

Understanding the scope of the this keyword is challenging, and TypeScript makes it a little easier by supporting arrow function expressions, a new feature being discussed for ECMAScript 6. Arrow functions preserve the value of this, making it much easier to write and use callback functions. Consider the following code:

var shape = {
	name: "rectangle",
	popup: function() {

		console.log('This inside popup(): ' + this.name);

		setTimeout(function() {
			console.log('This inside setTimeout(): ' + this.name);
			console.log("I'm a " + this.name + "!");
		}, 3000);

	}
};

shape.popup();

The this.name on line seven will clearly be empty, as demonstrated in the browser console:

We can easily fix this issue by using the TypeScript arrow function. Simply replace function() with () =>.

var shape = {
	name: "rectangle",
	popup: function() {

		console.log('This inside popup(): ' + this.name);

		setTimeout( () => {
			console.log('This inside setTimeout(): ' + this.name);
			console.log("I'm a " + this.name + "!");
		}, 3000);

	}
};

shape.popup();

And the results:

Take a peek at the generated JavaScript file. You'll see that the compiler injected a new variable, var _this = this;, and used it in setTimeout()'s callback function to reference the name property.


Classes with Public and Private Accessibility Modifiers

TypeScript supports classes, and their implementation closely follows the ECMAScript 6 proposal. Let's create another file, called class.ts, and review the class syntax:

class Shape {

	area: number;
	color: string;

	constructor ( name: string, width: number, height: number ) {
		this.area = width * height;
		this.color = "pink";
	};

	shoutout() {
		return "I'm " + this.color + " " + this.name +  " with an area of " + this.area + " cm squared.";
	}
}

var square = new Shape("square", 30, 30);

console.log( square.shoutout() );
console.log( 'Area of Shape: ' + square.area );
console.log( 'Name of Shape: ' + square.name );
console.log( 'Color of Shape: ' + square.color );
console.log( 'Width of Shape: ' + square.width );
console.log( 'Height of Shape: ' + square.height );

The above Shape class has two properties, area and color, one constructor (aptly named constructor()), as well as a shoutout() method. The scope of the constructor arguments (name, width and height) are local to the constructor. This is why you'll see errors in the browser, as well as the compiler:

class.ts(12,42): The property 'name' does not exist on value of type 'Shape'
class.ts(20,40): The property 'name' does not exist on value of type 'Shape'
class.ts(22,41): The property 'width' does not exist on value of type 'Shape'
class.ts(23,42): The property 'height' does not exist on value of type 'Shape'

Any JavaScript program is already a TypeScript program.

Next, let's explore the public and private accessibility modifiers. Public members can be accessed everywhere, whereas private members are only accessible within the scope of the class body. There is, of course, no feature in JavaScript to enforce privacy, hence private accessibility is only enforced at compile-time and serves as a warning to the developer's original intent of making it private.

As an illustration, let's add the public accessibility modifier to the constructor argument, name, and a private accessibility modifier to the member, color. When we add public or private accessibility to an argument of the constructor, that argument automatically becomes a member of the class with the relevant accessibility modifier.

...
private color: string;
...
constructor ( public name: string, width: number, height: number ) {
...
class.ts(24,41): The property 'color' does not exist on value of type 'Shape'

Inheritance

Finally, you can extend an existing class and create a derived class from it with the extends keyword. Let's append the following code to the existing file, class.ts, and compile it:

class Shape3D extends Shape {

	volume: number;

	constructor ( public name: string, width: number, height: number, length: number ) {
		super( name, width, height );
		this.volume = length * this.area;
	};

	shoutout() {
		return "I'm " + this.name +  " with a volume of " + this.volume + " cm cube.";
	}

	superShout() {
		return super.shoutout();
	}
}

var cube = new Shape3D("cube", 30, 30, 30);
console.log( cube.shoutout() );
console.log( cube.superShout() );

A few things are happening with the derived Shape3D class:

  • Because it is derived from the Shape class, it inherits the area and color properties.
  • Inside the constructor method, the super method calls the constructor of the base class, Shape, passing the name, width, and height values. Inheritance allows us to reuse the code from Shape, so we can easily calculate this.volume with the inherited area property.
  • The method shoutout() overrides the base class's implementation, and a new method superShout() directly calls the base class's shoutout() method by using the super keyword.
    • With only a few additional lines of code, we can easily extend a base class to add more specific functionality and make our intention known through TypeScript.


      TypeScript Resources

      Despite TypeScript's extremely young age, you can find many great resources on the language around the web (including a full course coming to Tuts+ Premium!). Be sure to check these out:


      We're Just Getting Started

      TypeScript supports classes, and their implementation closely follows the ECMAScript 6 proposal.

      Trying out TypeScript is easy. If you enjoy a more statically-typed approach for large applications, then TypeScript's features will enforce a familiar, disciplined environment. Although it has been compared to CoffeeScript or Dart, TypeScript is different in that it doesn't replace JavaScript; it adds features to JavaScript.

      We have yet to see how TypeScript will evolve, but Microsoft has stated that they will keep its many features (type annotations aside) aligned with ECMAScript 6. So, if you'd like to try out many of the new ES6 features, TypeScript is an excellent way to do so! Go ahead - give it a try!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Denis Leukhin

    Great. Thank you for missing info.

  • Tjums

    Here is a link to a danish webpage with a very informative movie about typescript at the bottom. Just in case anyone is interested. The movie is in english.

    http://www.comon.dk/art/220820/microsofts-danske-kodeguru-vil-goere-javascript-staerkere

  • Jesper lindstrøm

    Great article.. But i cant see the meaning in the language why not use Dart if you want something better than JS vanilla.. it gives you a lot more than TS.

    • codeBelt

      Because you don’t have to learn a new language to get the structure you want with JavaScript.

      • Fred G. Vader

        True, but if you don’t know JavaScript the learning curve is much easier for Dart. However this learning curve scenario is also an argument on why we need TypeScript. I loathe JavaScript and TypeScript is a godsend for C# devs like me looking to make the jump into the Html5/JavaScript world.

        Honestly I would love to see Dart take off. I think Google has the right idea in mind – I mean hindsight is 20/20 and we’ve got 20 years experience with the web now and they’ve taken that experience – wiped the slate clean and started over. Not only that programming in Dart is just like programming in C#.

        So the development experience using Dart is going to be pretty awesome once its matured. Browser adoption is a great concern though but as long is it can convert to JS it shouldn’t be too much of a barrier to entry. And if it doesn’t get widespread adoption there’s always TypeScript.

        The only thing that scares me about TypeScript is that one will probably have to maintain code from others that is an ugly mix of JavaScript style programming alongside TypeScript’s OO style. I’m seeing that a lot already in the various examples across the web. May not be an issue for those experienced with JavaScript but us newbies aren’t looking forward to it.

  • http://twitter.com/jeff_pz_cr Jeffrey Briceno

    It was created by ms, I do not become very popular for developers of free platforms like php, ruby, python and even static sites

    • http://villimagg.info/ Vilhjálmur Magnússon

      AJAX was also created by Microsoft and is used everywhere where JavaScript is found, weather it be in php applications and what not.

      • http://twitter.com/jeff_pz_cr Jeffrey Briceno

        Yes, I’m aware that ms produced ajax (It is quite ironic that MS fabricate the best thing about beacuse js IE suck), but it was not until google the attachment did not become popular.
        Typescript requires someone less hated that they use for it to become a standard as ajax

      • http://villimagg.info/ Vilhjálmur Magnússon

        Sure, IE sucks. But it doesn’t have to mean that all the developers at MS suck too. Maybe this is something good, and maybe not. How would you know, you’re not even going to give it a chance since your such an MS hater aren’t you?

        And then it’s never just black or white. Some MS products are the best on the market and some are the worst, and then there are some in between. Take MS Office f.ex. Do you mean to tell me that Office:Mac is better than MS Office? Or even worse: LibreOffice for Linux? wtf? crap!

        And then it’s the worlds most used, and at the same time the worlds worst web browser, MS IE. How do we as developers deal with the fact that the browser we so intimately hate is the worlds most popular browser? That is if popularity is defined by which browser is most used in the world.

        I mean, please don’t get me wrong. I’m not an MS fan or anything. I’m a Linux user myself and endorse open source technology. Everything I do is based on open source technology and I love it! But I’m not taking a stand against MS or anyone else. The world needs MS just as well as it needs Linux. And of all the developers at MS there must be someone who knows what he/she is doing and not everything is bad from the BIG BAD commercial companies. :)

        And as always I like to stay open for new things and keep an open heart :)

  • MPinteractiv

    great but pretty useless without vs2012 imho , other editors might get more support for typescript in the future though,but without vs refactoring tools and intellisence it feels like coding in java with vim.

    • Slavomir Durej

      not really , you can use other nice editors like Sublime and mature advanced IDEs like webstorm / phpstorm/IntelijIDEA from JetBrains that fully support Typescript including code hinting, code completion, error checking , syntax highlighting, code debugging etc during authoring time. I personally use PhpStorm for Typescript and it’s working very well!

  • sajay

    Nice tutorial, but not sure about the scope of this framework

  • blackheva

    I think coffee script is a better option

    • Jesper lindstrøm

      Well coffeescript gives you a “better looking javascript” and its nice cause its easy to write and express what you want..
      But coffeescript dosent give you what typescript does, typescript gives you type-checking safety that you know from static languages such as Java, Dart, C# etc. which is checked on compile time. Its good if you want to work in larger groups and/or larger communities.. but if you are the only one developing and you are comfortable in JS-vanilla or coffeescript it will be another notation you need to put down which is just annoying.

  • http://www.facebook.com/cicero.feijo Cícero Feijó

    Hmmm, in resume: a language created by Microsoft, and for a better experience you will need a modern browser likes “chrome” not IE, and if you don´t have time to install the mega big package of Visual Studio Express for Web (this setup install too the SQL Server – i don´t know why, but…) you can install the TypeScript using “npm install” in a console of “Linux”, (Visual Studio Developers knows what is a Linux Terminal??) and finally to create a “Hello World” in TS you can write “alert(‘Hello World’);”, this is like a Javascript, or not? :P – Sorry partner…

    • http://www.facebook.com/mayooresan Jeyakumaran Mayooresan

      I myself hate both MS and Apple but have the love for Google and Android. But just because MS is good at screwing doesn’t’ mean everything they do is useless.

      I think typescript will have its run. I’m on windows but never used visual studio. I’m an Andriod and nodejs developer. so I had no problem installing it using command prompt. You don’t have to own linux to run node and npm. It just works fine in windows.

  • codeBelt

    You forgot one nice resource: http://www.codebelt.com/typescript/

  • TheDudeWantsHisRugBack

    the dude approves TypeScript!!!

  • Васим Абу-Нассар

    Excellent article, thank you!

  • Rob McDiarmid

    The single quotes used in the sample code copy paste into my editor as a different quote character that doesn’t work. Good think TypeScript has compile time checking :). Thanks for the article.