ProgrammingJavascriptCareerProductivityGadgetsASP.NETWeb Design

How to Get Started With TypeScript

Written by
Published on
Modified on
Filed under
How to Get Started With TypeScript<br>

TypeScript is a free and open sourced superset of JavaScript created and currently maintained by Microsoft. It offers many OOP patterns that programmers are familiar with in other programming languages, and it compiles down to plain old JavaScript.

It offers good integration with Visual Studio as it can be installed as a NuGet package or as a Visual Studio Extension. Future ECMAScript specifications will include many of the same OOP features like classes and inheritance, but if you want to start building richer more OOP based JavaScript applications now, then this is the way to go.

Installing TypeScript

You have a few options when it comes to installing TypeScript on your machine. If you're using Visual Studio 2015 and above then you should already have the TypeScript project templates set up on your machine.

If you don't have it installed already, you can use the NuGet package manager in order to install it as well.

On applications that do not support NuGet, you can install the TypeScript compiler as a Visual Studio Extension.

And if you are not using Visual Studio for your coding, then you can also download TypeScript to your local projects using npm with the following command.

npm install typescript

Once installed, you can run the compiler on any .ts file using the following command.

tsc filename.ts

This will generate the compiled JavaScript back in the same directory.

Notable Features

TypeScript offers classes, modules, and interfaces to help you build robust components and to give you more OOP control of your code. TypeScript compiles down to plain old JavaScript that's compatible with most of today's browsers. You can install TypeScript as a Node.js package or if you're using Visual Studio 2015, then you already have it ready to go.

Starting a New Project

I'm going to start things up by creating a new TypeScript project in Visual Studio 2013. I'm just using 2013 because it's configured just the way I like it and I hate change. But the 2015 process is pretty much the same.

Getting Started With TypeScript Part 1

Getting Started With TypeScript Part 1

You'll be greeted with the usual IDE interface with a code area and a solution explorer. The solution comes with a default project that you can run and view immediately. I'll break down the project down below to give a better idea of how TypeScript comes together and the many benefits that having an OOP architecture in JavaScript have.

Classes and Variables


TypeScript supports classes just like every other OOP language. You can currently define classes in JavaScript using the usual Prototyping pattern that has plagued many sites, however, with TypeScript you can now do it in a manner more familiar to programmers and it will compile down to plain old JavaScript and run on most major browsers.



class Greeter {
    element: HTMLElement;
    span: HTMLElement;
    timerToken: number;

    constructor(element: HTMLElement) {
        this.element = element;
        this.element.innerHTML += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }


Like in most major languages, classes in TypeScript start with the class keyword. We can then give the class a name (identifier) and define inside of it class members, constructors and functions.


Variables


TypeScript supports the following basic data types to work with:

  • boolean
  • number
  • string
  • Array
  • Enum:

    enum Color {Red = 1, Green, Blue};
    var c: Color = Color.Green;

  • Any: This is a super useful feature of TypeScript. With the type any we can choose whether to opt-in or opt-out of any type checking in our applications. This is perfect for more dynamic situations where we may not know the type of the variables we are working with.
  • Void: The opposite of Any. We're telling the compiler that this variable has no type at all. Usually this is used for functions that have no return value associated with them.

Constructors


Constructors are called when classes are first instantiated. They can be overloaded and they're defined just with the identifier of the class that they reside in. In the example above, we have one constructor that takes in a parameter of type HTMLElement. You can reference the classes data members by using the this keyword followed by the data member name.


Class functions


You can also define your own functions inside of your class declarations.



    start() {
        this.timerToken = setInterval(() => this.span.innerHTML = new Date().toUTCString(), 500);
    }

    stop() {
        clearTimeout(this.timerToken);
    }
}


These are pretty much just regular JavaScript functions that have access to the data members defined in their enveloping classes. They can be called by first defining a class object and then prefixing the function names with that object.

And now that we have a basic class structure to work with, we can start using it by instantiating a new object of that type.



window.onload = () => {
    var el = document.getElementById('content');
    var greeter = new Greeter(el);
    greeter.start();
};


And because TypeScript compiles down to plain JavaScript, we'll end up with a new .js file. This is a very rudimentary example and you more than likely wouldn't create a new class and data members just to show a span with the time, but it shows just how clean you can make your code working with TypeScript.



var Greeter = (function () {
    function Greeter(element) {
        this.element = element;
        this.element.innerHTML += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }
    Greeter.prototype.start = function () {
        var _this = this;
        this.timerToken = setInterval(function () { return _this.span.innerHTML = new Date().toUTCString(); }, 500);
    };
    Greeter.prototype.stop = function () {
        clearTimeout(this.timerToken);
    };
    return Greeter;
})();
window.onload = function () {
    var el = document.getElementById('content');
    var greeter = new Greeter(el);
    greeter.start();
};
//# sourceMappingURL=app.js.map


A Few More Advanced Topics


Defining classes is just one of the many features that TypeScript provides. You can also make use of inheritance, interfaces, modules and cross-file compilation.


Inheritance


TypeScript also supports class inheritance and it works just as it does in many other languages like C# and Java. In order to inherit from a parent class in TypeScript you will need to use the extends keyword.



class Person{
    name: string;
    private Identifier: number;

    constructor(theName: string)
    {
        this.name = theName;
    }

    Register()
    {
        // perform some action here
     }
}

class Student extends Person{
    constructor(theName: string)
    {
        super(theName);
    }

    Register()
    {
        // perform some other action
        super.Register();
    }
}


There are a few things going on in the example above. First, notice that we can extend another class by using the extends keyword. And that we can call upon the parent classes members and functions by prefixing them with the super keyword. Child classes in TypeScript can override their parent classes functions, like in many other languages as well.

Also important to note is that you can give data members their own private/public modifiers. In the example above, the Person class contains a private data member Identifier which will not be accessible to the subclass.


A Few Last Words


TypeScript is a great addition to any programmers list of talents. Particular for more code oriented developers that find themselves working heavily on client side code. This was just a small primer for TypeScript noobs, but part 2 is coming soon with much more practical examples. Happy Coding!

Walter Guevara is a software engineer, startup founder and currently teaches programming for a coding bootcamp. He is currently building things that don't yet exist.

Comments

No messages posted yet

Developer Poll

Q:

Stay up to date

Sign up for my FREE newsletter. Get informed of the latest happenings in the programming world.

Add a comment

Keep me up to date on the latest programming news
Add Comment

Stay up to date

Get informed of the latest happenings in the programming world.

No thanks