Setting up Typescript for Sublime Text on Mac

Typescript is a superset of Javascript and it compiles back to Javascript, which means valid Typescript is valid Javascript.

Most of the examples/tutorials you find online for typescript shows how to write typescript on visual studio.I am not a big fan of bloated IDE's ( nothing personal ) , but really like typescript as it provides structure to Javascript.

Let's spend some time in order to setup typescript for sublime text.

Step 1 ( Download Typescript )

Downloading typescript using npm as a global module on your working machine.

npm install -g typescript  

And ofcourse you need nodejs in order to run npm commands.

Step 2 ( Download sublime plugin )

Grab copy of sublime text plugin from this blog post

  1. Download and extract zip folder
  2. Copy typescript.tmLanguage to ~\Library\Application Support\Sublime Text 2\Packages\User

Step 3 ( Configure build system )

Go to Tools->Build System->New Build System from sublime text menu , copy following code into that file and save it as typescript.sublime-build

{
    "cmd": ["tsc","$file"],
    "file_regex": "^(.+?) \\((\\d+),(\\d+)\\)(: .+)$",
    "line_regex": "\\((\\d+),(\\d+)\\)",
    "selector": "source.ts",
    "osx": {
       "path": "/usr/local/bin:/opt/local/bin"
    }
}

If all is good till this point , then we are ready to write our first Typescript program.

Create a newfile anywhere with .ts extension and copy below code to your file.

class Greeter {  
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

var greeter = new Greeter("world");

var button = document.createElement('button');  
button.textContent = "Say Hello";  
button.onclick = function() {  
    alert(greeter.greet());
}

document.body.appendChild(button);

Now select typescript as the build system from sublime text menu.

typescript as build system

and next click on build to output javascript file.

The End

That is all required in order to use typescript inside sublime text, if you are great lover of build system then you can also use following plugins for grunt or gulp.

grunt typescript

gulp typescript