Skip to main content

Microsoft TypeScript : A quick introduction and A Love Affair Begins here.

Alright, I knew this was coming. At least, I inferred. When I went to Microsoft few months back to attend the MVP summit, we had an awesome session from Anders, and I asked him what is the future of C#. He muttered something like “JavaScript is the true cross platform language” (Did I hear that right?)

imageAnd there was some speculation that Anders was working on something related to JavaScript. And now, Typescript is here. TypeScript is a neat little language that compiles in to JavaScript, and the compiled output is readable and pretty printed it seems, so that you can use the compiled JavaScript directly where ever you want. I played around with Typescript, and it looks pretty neat (Yea, I’m repeating the term ‘neat’). The syntax has some magical similarity to the aesthetics of C# (or that was my feeling?). I’ve seen few people wondering whether TypeScript is Microsoft’s version of Dart or whether it is some kind of Coffee Script on Steroids – but after trying TypeScript out for sometime, I’m in love with Typescript. I was making some notes, and combined them for this blog post.

You can install Typescript from here , and then in Visual Studio, try creating an HTML application with Typescript. (OSS Fans Cheer up, Support for VI, Sublime and Emacs is also available)

image

A Quick Hello World in TypeScript

Here is a quick hello world script I wrote using Typescript.  You can see the type script file (app.ts), and the generated app.js file.  As I mentioned, the syntax is very much similar to C#. And the big surprise – as the name indicates, TypeScript supports ‘Types’.  See my HelloWorld class below, I’m having a constructor which takes an HTMLElement, and I’ve got a sayHello method that accepts a message of type string. I feel having these type contracts will be a big boon because that’ll help programmers to specify expected types for a function.

image

 

Here is the Typescript code, and generated Javascript code. While working in Visual Studio, I’ve noticed that Visual Studio Typescript editor provides type inference, that’s cool. See my HelloWorld class – pretty self explanatory.

//Our TypeScript HelloWorld class

class HelloWorld {
    
    //A variable of type HTMLElement
    element: HTMLElement;

    //A Consctructor that accepts an element
    constructor (e: HTMLElement) { 
        this.element = e;
    }

    //A public method
    sayHello(message: string) {
        this.element.innerHTML = message;
    }

}

window.onload = () => {
    var e = document.getElementById('content');

    //Initiate HelloWorld Class
    var hello = new HelloWorld(e);
    hello.sayHello("Hello World");
};
Awesome. Now, here is the generated Javascript code, that's equivalent to the above Typescript code. Neat and clean generation.  
var HelloWorld = (function () {
    function HelloWorld(e) {
        this.element = e;
    }
    HelloWorld.prototype.sayHello = function (message) {
        this.element.innerHTML = message;
    };
    return HelloWorld;
})();
window.onload = function () {
    var e = document.getElementById('content');
    var hello = new HelloWorld(e);
    hello.sayHello("Hello World");
};

You can even use scope keywords in your TypeScript class - try making the element variable private, and sayHello method public. I also skimmed through the Type Script specification, and here are few other interested points I noticed apart from the Types support. 

Function Types

Typescript uses Function Types for handling call backs. Let us modify the above code, to have a call back. See that I've added a notify parameter to our sayHello method of type

(feedback : string)=>any

This simply represents a function which takes a an input parameter of type string, and returns ‘any’ back to the caller (See ‘any’ type below). Upon the completion of sayHello, we are calling the notify(..) back, which will invoke the function(..) we passed to sayHello from window.onload – This is almost like passing a Function over a delegate type and invoking it back in the C# sense..

//Our TypeScript class now with Callbacks

class HelloWorld {
    
    //A variable of type HTMLElement
    element: HTMLElement;

    //A Consctructor that accepts an element
    constructor (e: HTMLElement) { 
        this.element = e;
    }

    //A public method. See notify paramter is now taking a Function Type
    sayHello(message: string, notify: (feedback : string)=>any ) {
        alert(message);
        //Do some other complex stuff here
        notify("completed sayHello");
    }

}

window.onload = () => {
    var e = document.getElementById('content');

    //Initiate HelloWorld Class
    var hello = new HelloWorld(e);
    hello.sayHello("Hello World", function (feedback) {
            alert(feedback);
        }
    );
};

Run the project, fire up the HTML page, and you’ll see the first message box with “hello world”, and second message box with “completed sayHello” message. Pretty cool. We just learned how to write type safe call backs in TypeScript, elegantly, with out worrying about closures

Object Types

An Object type looks like { parameter1: type1, parameter2: type2, … }. Example is

{name: string, age: number}
You can give a name to an object type, like this.
 interface Human 
   {
    name: string, 
    age: number
   }

Once you define an interface, you can use it as a contract, for specifying input, for return types, for call backs etc, with full Intellisense support. See below.

image 

A Bit more about Types in Typescript

TypeScript has multiple types. Here is a quick overview

‘any’ type

“Any Type is a super set of all types”

  • Example:
    • var x : any; //x is explicitly typed to any
    • var y; //type of y is any by default as no other type is specified

Primitive Types

TypeScript supports number, bool, string, null and undefined

  • Example
    • Number
      • var num : number;
      • var num = 20; //number type will be automatically inferred for num variable, same as var num : number = 20
    • String
      • var name : string;
      • var message=”hello”; //string type will be automatically inferred for message variable
    • Bool
      • var isOpen : bool;
      • var isEnabled=true; //bool type will be automatically inferred for isEnabled variable

‘void’ type

Used as the return type of functions that don’t return any value

Object Types

This include class, interface, module and literal types. These Object types contain one or more

  • Properties
  • Call signatures (Parameters and return types associated with a call operation)
  • Construct signatures (Parameters and return types associated with applying the ‘new’ operator)
  • Index signatures
  • Brands (Brands are categories the given object type belongs to)
    • More about this later. Examples
      • Object obj = {name : “Vinod”, age: 30 };
      • Function square = (x: number)=> x * x; //Almost like the lambda syntax in C#

Conclusion

Overall, I found that there is a strange attraction factor that connects C# developers with Type Script. I was able to start with out much hassle, and was able to grasp the basics in a couple of hours. Of course, introducing types ( CLARIFIED: i.e, types for enabling well defined contracts for functions, input parameters, return types etc) on a meta level and still maintaining the dynamic feature of JavaScript is a big thing as this means better refactoring, easier maintainability and better documentation. Enjoy TypeScript, I’m pretty sure I’ll write more about this pretty soon. I’m in love with Typescript.

 

Update: Checkout the second part, Type Script Language Features – Classes, Inheritance and Overriding >>

Popular posts from this blog

Top 7 Coding Standards & Guideline Documents For C#/.NET Developers

Some time back, I collated a list of 7 Must Read, Free EBooks for .NET Developers, and a lot of people found it useful. So, I thought about putting together a list of Coding Standard guidelines/checklists for .NET /C# developers as well.As you may already know, it is easy to come up with a document - the key is in implementing these standards in your organization, through methods like internal trainings, Peer Reviews, Check in policies, Automated code review tools etc. You can have a look at FxCop and/or StyleCop for automating the review process to some extent, and can customize the rules based on your requirements.Anyway, here is a list of some good Coding Standard Documents. They are useful not just from a review perspective - going through these documents can definitely help you and me to iron out few hidden glitches we might have in the programming portion of our brain. So, here we go, the listing is not in any specific order.1 – IDesign C# Coding StandardsIDesign C# coding stand…

Hack Raspberry Pi – How To Build Apps In C#, WinForms and ASP.NET Using Mono In Pi

Recently I was doing a bit of R&D related to finding a viable, low cost platform for client nodes. Obviously, I came across Raspberry Pi, and found the same extremely interesting. Now, the missing piece of the puzzle was how to get going using C# and .NET in the Pi. C# is a great language, and there are a lot of C# developers out there in the wild who are interested in the Pi.In this article, I’ll just document my findings so far, and will explain how develop using C# leveraging Mono in a Raspberry Pi. Also, we’ll see how to write few minimal Windows Forms & ASP.NET applications in the Pie as well.Step 1: What is Raspberry Pi?Raspberry Pi is an ARM/Linux box for just ~ $30. It was introduced with a vision to teach basic computer science in schools. How ever, it got a lot of attention from hackers all around the world, as it is an awesome low cost platform to hack and experiment cool ideas as Pi is almost a full fledged computer.  More About R-Pi From Wikipedia.The Raspberry Pi

5 Awesome Learning Resources For Programmers (To help you and your kids to grow the geek neurons)

Happy New Year, this is my first post in 2012. I’ll be sharing few awesome learning resources I’ve bookmarked, and will be pointing out some specific computer/programming related courses I've found interesting from these resources.Also, thought about saving this blog post for my kids as well - instead of investing in these Child education schemes (though they are too small as of today, 2 years and 60 days respectively ). Anyway, personally my new year resolution is to see as much videos from this course collections (assuming I can find some free time in between my regular job && changing my babies diapers).1 – Khan AcademyAs I mentioned some time back, you and your kids are missing some thing huge if you havn’t heard about Khan Academy.  It is an awesome learning resource, especially if you want to re-visit your basics in Math, Science etc.With a library of over 2,600 videos covering everything from arithmetic to physics, finance, and history and 268 practice exercises, th…