14 Days Free Technical Video Training from WintellectNOW

  

TypeScript: A New Language for .NET and JavaScript Developers

Tags: TypeScript, JavaScript, Web Development, App Development, Software Development

JavaScript is quite possibly the world's most popular programming language. It's nearly impossible to have a website without it. Despite its wild popularity, JavaScript does play some tricks on unsuspecting developers and sometimes does not work as expected, especially from a C# coder's point of view. It's also easy for JavaScript to run amok throughout a project, especially if it is not organized well, both in files and via patterns. This is where TypeScript comes into the picture. TypeScript works excellently as a shim for C# developers who must write JavaScript. In addition to that, JavaScript developers will enjoy TypeScript's implementations of ES6 proposed features (i.e., classes) that put it on syntax parity with OOP languages. That's not to mention while many hardened JavaScripters out there already know how to do all the things TypeScript provides, it still has much nicer syntax than JavaScript's prototypal way of doing it. (of course, the look of syntax is always an opinion; which is better, vanilla or chocolate?)

TypeScript is not a new language as it is a superset of JavaScript that compiles to plain JavaScript. This isn't "compile" in the traditional sense of the word, but that TypeScript is JavaScript that generates more JavaScript. The TypeScript compiler, tsc.exe, creates the prototypal syntactical code as well as the implementation of classes, namespaces, and types. There are no TypeScript designers in Visual Studio (good) and the JavaScript outputted is generally clean and lightweight.  

Why Use TypeScript? TypeScript Features

You only need to install TypeScript for Visual Studio 2012 and 2013 and you're ready to go. Visual Studio will support TypeScript's .ts files as well as perform "on save" compilations automatically when editing .ts files. While browsing TypeScript online you'll find links to the TypeScript source code and the language specs [.pdf]. TypeScript's mission is to enable JavaScript developers to write complex software with JavaScript that is also maintainable by enabling the following language features:

  • ES6 proposed features, now
  • Easier OOP with classes, interfaces, and inheritance.
  • Parameter and return types as well as type inference
  • Bacon, rainbows, and unicorns[1]
  • Arrow function syntax (Lambda style)
  • Generics
  • Type checking
  • Lots of other good stuff

You can use TypeScript at the TypeScript playground online or in Visual Studio 2012 when you install TypeScript. In Visual Studio 2013 and later, TypeScript is baked right in and there is no need for a separate download. Upon a successful installation you'll find a TypeScript project template and integration between Visual Studio and TypeScript such as Intellisense and the ability to manage .ts files in Solution Explorer.

While Visual Studio boasts of tight integration with TypeScript, each time you save (default behavior) your .ts code it runs the tsc.exe compiler to generate JavaScript output. You can run tsc.exe from the Package Manager Console or an OS command prompt.

A TypeScript Program

You can organize programs in TypeScript much like namespaces in .NET, except in TypeScript we use the module keyword. To create an object model you can nest modules and classes, as the code sample below shows. Notice the export keyword applied to the Models module and the BankAccount class. For C# or VB.NET folks, that makes them public.

module BankOfRachii
{
    export module Models
    {      
        export class BankAccount
        {
            AccountId: string;
            AccountHolderName: string;

            private _balance: number;
            get Balance(): number
            {
                return this._balance;
            }
        }
    }
}

TypeScript generates the output below from the code above:

var BankOfRachii;
(function (BankOfRachii) {
    (function (Models) {
        var BankAccount = (function () {
            function BankAccount() {
            }
            Object.defineProperty(BankAccount.prototype, "Balance", {
                get: function () {
                    return this._balance;
                },
                enumerable: true,
                configurable: true
            });
            return BankAccount;
        })();
        Models.BankAccount = BankAccount;
    })(BankOfRachii.Models || (BankOfRachii.Models = {}));
    var Models = BankOfRachii.Models;
})(BankOfRachii || (BankOfRachii = {}));
//# sourceMappingURL=gen.js.map

This is the module pattern at work. In JavaScript, the module pattern is a way to organize your code in a way that is especially valuable in projects with large volumes of JavaScript. Modules contain JavaScript in units that if properly designed make it easy to pull a single module out for bug fixes without disturbing others and introducing new bugs. You can of course code this yourself but as you see, TypeScript gives you syntactic sugar so you can code faster if your background is from C# or statically typed, object oriented, languages.

TypeScript organizes code in modules and compiles using the tsc.exe compiler into pure JavaScript using industry standard patterns such as the module pattern. As you go deeper into TypeScript you'll see how to put other patterns put into use as well.

TypeScript Type System

TypeScript adds an optional type system to JavaScript, so that you can declare variable, argument, and return types. Consider the syntaxes in following BankAccount class. You can see a colon then the type is the syntax that forms types for fields, properties, arguments, and return types.

export  class BankAccount implements IFees
{
    AccountId: string;
    AccountHolderName: string;

    constructor(acctId: string)
    {
        this.AccountId = acctId;
        this._balance = 0;
    }

    private _balance: number;
    get Balance(): number
    {
        return this._balance;
    }

    private _interestRate: number;
    get InterestRate(): number
    {
        return this._interestRate;
    }
    set InterestRate(value: number)
    {
        this._interestRate = value;
    }

    public Deposit(amount: number): boolean
    {
        this._balance += amount;
        return true;
    }

    Withdraw(amount: number): boolean
    {
        if (this._balance > amount)
        {
            this._balance -= amount
    return true;
        }
        return false;
    }

    ChargeFee(amount: number)
    {

        this._balance -= amount;
    }
}

The AccountId, AccountHolderName and Balance fields and properties in the above sample are all typed. The arguments are typed in the constructor which accepts a string. The Deposit, Withdraw, and ChargeFee methods all use typed arguments and returns. Trying to assign a value that is of the wrong type will result in a compile error by the TypeScript compiler. The "Type" in TypeScript should be very clear at this point.

TypeScript and Object Oriented Programming

TypeScript is more than just types, since it can implement the major principles of OOP. This is illustrated in the sample above as the class keyword does not exist in JavaScript proper (although classes but not necessarily the keyword are an ES6 proposal). Also seen in the example is encapsulation, one of the four principles of object oriented development. Encapsulation is implemented through the properties and methods. The BankAccount class also contains getter and setter property syntax, a syntax style not found in plain JavaScript as you must use prototype syntax there, and that is what TypeScript generates for you.

In addition to basic classes is the notion of inheritance as well as abstraction through interfaces. You can use the interface keyword to define an interface and the implements keyword to apply it. Below is an interface definition,

export interface IFees { ChargeFee(amount: number); }

and a sample of it applied to the BankAccount class. Of course the BankAccount class must implement all members of the interface (in this case only one), like the code below:

export class BankAccount implements IFees
{
    ChargeFee(amount: number)
    {
        this._balance -= amount;
    }
}

Along with interfaces comes the extends keyword to extend a base class and inherit as well as getters and setters (via get and set keywords). You can setup full object models using all of the OO principles.

How TypeScript Compares to Coffee Script

TypeScript vs. CoffeeScript: The thing to remember is that TypeScript is JavaScript while Coffee Script is not JavaScript but a different language that transcompiles to JavaScript. Both try to solve many of the same problems that arise when writing JavaScript for enterprise projects and they do although in different ways. This doesn't necessarily make one better than the other, but I prefer TypeScript's syntax as opposed to Coffee Script's.

Summary

You can write and edit TypeScript in JetBrain's WebStorm and new editors for TypeScript are shipping frequently and the tsc.exe compiler creates a sourcemap file so you can debug TypeScript with your favorite debuggers, including Visual Studio.

TypeScript works well in both apps and code, as you can incorporate TypeScript into any ASP.NET web site (Web Forms/MVC/Web Pages) as well as any client app such as Windows Store JavaScript apps.

BONUS: TypeScript makes a great teaching tool! Teach OOP with TypeScript and JavaScript in mind and you get two samples for every demonstration.

 

[1] These are not actual TypeScript features. It's too late anyway, I already ate the bacon.

5 Comments

  • rachel said

    Leniel/David,

    This is what happens when you copy and paste then don't run unit tests! LOL Fixed!

  • sofia said

    TypeScript is a lovely thing. I'd really like to use it.

    Most of my JavaScript development is in NodeJs. The major problem is TypeScript and NodeJs don't make good friends.

  • Leniel Macaferi said

    Rachel,

    Great write up about TypeScript!

    Only one "MAJOR" bug in the code: use -= and not += when withdrawing. I'd love if my bank used the += instead as you did... LOL :)

    Withdraw(amount: number): boolean
    {
    if (this._balance > amount)
    {
    this._balance -= amount
    return true;
    }

    return false;
    }

Comments have been disabled for this content.