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

An introduction to Type Script

4.92/5 (7 votes)
2 Oct 2012CPOL5 min read 59.1K  
A quick introduction to Typescript - Classes, Callbacks, Interfaces, Function Types, and Object Types etc

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?) 

image

And 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 normally use Javascript. 

Introduction 

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 post. I felt TypeScript is more 'aligned' with Javascript (not an alien syntax like Coffeescript), and also the generated output is human readable unlike Coffee Script output. And there is much more to Typescript - Enabling typed contracts for functions, call backs, return types and much more. 

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. 

A Bit more about Type based contracts 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.  Follow Me in Twitter and absolutely Follow My Blog 

 

 

 

License

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