Getting Started with TypeScript

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)
  2. Install the TypeScript npm package globally in the command line:
  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:

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:

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

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

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:

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

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:

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:

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:

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:

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 () =>.

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:

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:

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.


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:

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!

Tags:

Comments

Related Articles