Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Typescript

An Introduction to TypeScript

5.00/5 (5 votes)
16 Feb 2015CPOL6 min read 14K  
An introduction to TypeScript

typescript

Introduction

Last summer I chose JavaScript as an area of focus. When I blogged about this, one of the comments suggested I take a look at TypeScript (thanks Federico). Since that time, I have started using TypeScript and with the recent release of TypeScript 1.4, it seemed like a good time to write an introduction to TypeScript for those who are unfamiliar with it.

What is TypeScript?

On its website, TypeScript is defined as follows:

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

Breaking that statement down, we can learn something about what TypeScript is.

First of all, TypeScript is typed. That doesn’t mean that you write TypeScript using a keyboard, it means that unlike JavaScript, TypeScript considers the types of variables, parameters and functions. Many of us learned to code in a typed language, such as Java or C#. In statically typed languages such as these, the compiler checks our code at compile-time for type errors.

Secondly, TypeScript is a superset of JavaScript. In other words, the TypeScript language specification includes everything that is in JavaScript, with some additional syntax added. You could decide to use TypeScript and then just write everything in ‘plain’ JavaScript in your TypeScript file, if you really wanted to. The TypeScript compiler would understand everything you had written, and just write the same script into a JavaScript file.

Which brings us to our third point – TypeScript compiles into plain JavaScript. JavaScript doesn’t require compilation into anything, it is just executed by the browser in its original form. Browsers do not understand TypeScript’s added syntax, therefore it is compiled by the TypeScript compiler into plain JavaScript which can be understood by the browser.

Two further points worth mentioning, which aren’t included in the definition above, are that TypeScript is open source, and it is developed and maintained by Microsoft. You can take a look at the code on github, and even contribute to the project.

Working with TypeScript

In order to use TypeScript, we need the TypeScript compiler, and we need to write our script in files with a “.ts” extension. If you are coding using Visual Studio 2013 or 2015, then you are ready to go, as these environments include the TypeScript compiler. For other environments, you may need to download and install the TypeScript compiler. Details are on the website.

TypeScript’s Features

Type annotations allow you to assign types to variables, parameters and functions. The TypeScript compiler will then alert you to type errors at compile time.

JavaScript
var x: string = 'hello lad';

function square(n: number) : number
{
   return n*n;
}

var n = square(x); // this will throw a compilation error

In addition to checking for type errors, the TypeScript compiler will also check the structure of your code. For example, in addition to checking the types of arguments passed to a function, it will check the number of arguments passed. In plain JavaScript of course, you can call a function with any number of arguments, which may or may not be intentional, where extra arguments are ignored and missing arguments are set to null. TypeScript forces you to be explicit about your intentions, removing the possibility of accidental misuse.

JavaScript
function square(n: number) : number
{
   return n*n;
}

var n = square(); // this will throw a compilation error (no arguments)

TypeScript has seven basic types which are self-explanatory: Boolean, Number, String, Array, Enum, Any and Void. The Any type can be used when we do not know what the type of a variable will be.

Interfaces can be used in TypeScript to take advantage of object-oriented principles. For an object to be accepted by the compiler as adhering to an interface, it must contain at least the properties and functions defined by the interface. If it contains more, then that is fine. Members of an interface can also be defined as optional, in which case they need not be present on the implementing object.

JavaScript
interface Product {
   name: string;
   price: number;
   description?: string; // the question mark makes this optional
}

As you may have guessed, TypeScript also supports classes and inheritance.

The class keyword is introduced, simplifying the idea of using functions in JavaScript to simulate object-oriented classes. Class members can be declared as public, private or static, again moving us closer to an object-oriented approach, and we can also declare constructors on a class.

JavaScript
interface Product {
   name: string;
   price: number;
   description?: string; // the question mark makes this optional
}

class Shirt implements Product {
   private size: string;
   name: string;
   price: number;
}

There are many other useful features in TypeScript including generics, lambdas and modules. Further details on these can be found in the TypeScript handbook.

The Benefits of Using TypeScript

The advantages of using TypeScript can be broadly divided into two categories.

Firstly, it offers type checking. This allows us to identify errors earlier, and potentially save hours of debugging our JavaScript code. As discussed in Crockford’s JavaScript: The Good Parts, JavaScript’s best features are also its most dangerous. Dynamic typing offers flexibility, but it can also be conducive to bugs. With TypeScript, you could say we get the best of both worlds. If you want to take advantage of JavaScript’s dynamic typing, then just write plain JavaScript in your TypeScript file, but under most circumstances we don’t need dynamic typing, and so we can make use of TypeScript’s type annotations.

Secondly, TypeScript allows and encourages us to write object-oriented code. The fundamental principles of object-oriented programming are often referred to as abstraction, encapsulation, inheritance and polymorphism. TypeScript makes it easier for us to follow principles such as these. Class definition syntax helps us to abstract. Public and private access modifiers help with encapsulation, and TypeScript has inheritance syntax built-in. In short, if you believe in object-oriented programming, and you need to write JavaScript, then TypeScript may be for you. Even if you don’t understand the benefits of object-oriented programming, if that approach is all you know, then TypeScript will help you to write better JavaScript.

Aside from these technical advantages, the fact that TypeScript is a superset of JavaScript means that you can make the transition to using TypeScript gradually. Start writing plain JavaScript in TypeScript files, and gradually introduce more of TypeScript’s features as and when you learn and decide to use them.

The Disadvantages of Using TypeScript

I see very few if any disadvantages of using TypeScript. Some have complained that the compiler is slow, which may be the case for very large code bases, but I personally haven’t experienced any slowness in compilation.

Another possible disadvantage is the problem of integrating with third-party libraries. How do you assign a variable to a “type” which is defined in a library? There are workarounds for this. One is to create a declaration file for the library, however while this may be a disadvantage compared to other similar languages (I have not looked into how Dart or CoffeeScript handle this problem), it is certainly not a disadvantage over using plain JavaScript. After all, we don’t have to annotate variables with types.

Final Words

If you are familiar with object-oriented programming, or you believe in its benefits, and you need to write JavaScript, then TypeScript is a great choice. The fact that it is a superset of JavaScript means that you can easily “migrate” an existing code base to TypeScript without actually altering your code. If you are starting a new project, you can adopt TypeScript without many of the usual challenges faced when switching to a new language. Because in reality, TypeScript is not a new language. It is more like a new and improved version of JavaScript.

The post An Introduction to TypeScript appeared first on The Proactive Programmer.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)