Friday, October 18, 2013

TypeScript Hello Word

In this blog I will walk you through on how creating a JavaScript “Hello World” using TypeScript is similar to the C# or VB.NET’s “Hello World” app.

I will first create a Greeter class in C# which will return Hello World message when invoked. Later I will show how this class can be converted to a JavaScript’s Hello World with minimal changes, without learning or using JavaScript.

Here is my C# code of the Greeter class which greets when invoked.

    public class Greeter
    {
        string greeting;
        public Greeter(string message)
        {
            this.greeting = message;
        }

        public string Greet()
        {
            return "Hello " + this.greeting;
        }
    }

This Greeter can be invoked in a MVC view as mentioned below

    var greeter = new Greeter("World");
    @Html.Raw(greeter.Greet());

In order to convert this Greeter C# class to Greeter TypeScript class (or Greeter JavaScript function) you need to make the following two minimal changes:
  • In TypeScript there is no scope for class declaration. Hence public is not needed and need to be removed
  • The datatype declaration is different from the C# code. These are the changes for the data type declaration
    • string greeting -> greeting: string
    • string Greet() -> Greet() : string
Here is the TypeScript code for our Greeter class

    class Greeter
    {
        greeting: string;
        constructor(message : string)
        {
            this.greeting = message;
        }

        public Greet() : string
        {
            return "Hello " + this.greeting;
        }
    }

There is no change to the invoking code. As we are invoking this Greeter class from TypeScript instead of View, we have to change HtmlHelper to JavaScript alert

    var greeter = new Greeter("World");
    alert(greeter.Greet());

As you see with minimal changes we converted our C# code to TypeScript. Here is code in both C# and TypeScript juxtaposed.

C#
TypeScript
public class Greeter
{
    string greeting;
    public Greeter(string message)
    {
        this.greeting = message;
    }
    public string Greet()
    {
        return "Hello " + this.greeting;
    }
}
class Greeter
{
    greeting: string;
    constructor(message : string)
    {
        this.greeting = message;
    }
    public Greet() : string
    {
        return "Hello " + this.greeting;
    }
}
var greeter = new Greeter("World");
@Html.Raw(greeter.Greet());
var greeter = new Greeter("World");
alert(greeter.Greet());

As you see how natural it is for C# or VB.NET developer to move and adopt TypeScript in your code.

Please go to my TypeScript blog series for other blogs in TypeScript.

No comments:

Post a Comment