Sunday, December 15, 2013

Learning TypeScript: Hello World

I'm finding more and more developers are growing an interest in Typescript.  When I first started learning the language, I started with the samples here:

I'm starting a series of blog posts on each of these samples.  I'm taking the notes I wrote when I first started learning TypeScript, and updating them with my current understanding. The samples start quite simple. Each sample adds new concepts and new examples.

The first sample is your basic Hello World sample.  You can see it running here:

Exciting, I know.

The source code is a bit more interesting. You can see it online here. It shows some of the important concepts in Typescript:

The HTML source for this sample shows an empty page that loads a single .js file:

 <!DOCTYPE html>
  <head><title> TypeScript Greeter </title></head>
    <script src='greeter.js'></script>

The source is not a JavaScript file, but rather a TypeScript file: greeter.ts. That's the first important concept: Typescript files are compiled to JavaScript files.  TSC (Typescript compiler) generates the greeter.js file from the greeter.ts file shown here:

class Greeter {
    constructor(public greeting: string) { }
    greet() {
        return "<h1>" + this.greeting + "</h1>";
var greeter = new Greeter("Hello, world!");
var str = greeter.greet();
document.body.innerHTML = str;

Read more: BillWagner