TypeScript

JavaScript for tools

Ben Smith ben@10consulting.com

TypeScript is a language for application-scale JavaScript development.


TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.


Any browser. Any host. Any OS. Open Source.

typescriptlang.org

Design Goals

What TypeScript does is, it basically formalizes a static type system that describes JavaScript's dynamic types, but it describes them at development time.

Anders Hejlsberg

Tooling Support

Currently supported in Visual Studio 2012 and Microsoft's Monaco web editor (TypeScript.org playground).

Also, text editor support for Sublime Text, EMACS, Vim.

Installation

Visual Studio 2012

Plugin available to download.

Node.js

npm install -g typescript

Provides a command-line compiler.

tsc source.ts

File Extensions

Declaration Source Files

Type Annotations

function add(a: number, b: number) {
    return a + b;
}

Types

Primitive Types

Object Types

Arrow Function Expressions

var messenger = { 
  message: "Hello World", 
  start: function() { 
    setTimeout(() => { alert(this.message); }, 3000); 
  } 
}; 
messenger.start();
window.onmousemove = e => {
  console.log('Mouse at ('+e.screenX+','+e.screenY+')');
}

Classes

Classes

class Animal {
    constructor(public name) { }
    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
  move() {
    alert("Slithering...");
    super.move(5);
  }
}

class Horse extends Animal {
  move() {
    alert("Galloping...");
    super.move(45);
  }
}

Interfaces

Interfaces

interface Drivable {
    start(): void;
    drive(distance: number): void;
    getPosition(): number;
}

class Car implements Drivable {
  private isRunning: bool = false;
  private distanceFromStart: number;
  
  public start(): void {
    this.isRunning = true;
  }
  public drive(distance: number): void {
    if (this.isRunning) {
      this.distanceFromStart += distance;           
    }        
  }
  public getPosition(): number {
    return this.distanceFromStart;
  }
}

Note interfaces have no run-time representation - they are purely a compile-time construct.

Structual Types

interface Person {
    firstname: string;
    lastname: string;
}

function greeter(person: Person) {
    return "Hello, " + person.firstname + " " + person.lastname;
}

var user = {firstname: "Jane", lastname: "User"};

greeter(user);

Note that strutural typing also applies to interface methods.

Modules

Modules

interface IPoint {
    getDist(): number;
}

module Shapes {
  // Class exported for public consumption
  export class Point implements IPoint {
      // Constructor
      constructor (public x: number, public y: number) { }

      // Instance member
      getDist() { return Math.sqrt(this.x * this.x + this.y * this.y); }

      // Static member
      static origin = new Point(0, 0);
  }
}
var p: IPoint = new Shapes.Point(3, 4);
var dist = p.getDist();

Source File Dependencies

Reference comment

/// <reference path="jquery.d.ts"/>

Import declaration

import log = module("log"); 
log.message("hello");

Source Map Support

tsc -sourcemap example.ts

Demo

Self hosting

Hosting TypeScript Compiler

1. Create an html file with a reference to typescript.js file.

<script type="text/javascript" src="typescript.js"></script>

2. Create an output writer

var outfile = {
    source: "",
    Write: function (s) {
        this.source += s;
    },
    WriteLine: function (s) {
        this.source += s + "\n";
    },
    Close: function () { }
};

3. Create an instance of the TypeScript compiler

var compiler = new TypeScript.TypeScriptCompiler(outfile);

... with compilation error handling.

compiler.parser.errorRecovery = true;
compiler.setErrorCallback(function (start, len, message, block) {
    console.log('Compilation error: ', message, '\n Code block: ', block, ' Start position: ', start, ' Length: ', len);
});

4. Add compilation source.

var src = $('#source').text();
compiler.addUnit(src, '');

... and standard lib file.

// libfile variable contains packed declaration file lib.d.ts
compiler.addUnit(libfile, 'lib.d.ts');

5. Compile.

compiler.typeCheck();

compiler.emit(false, function createFile(fileName) {
    console.log(outfile);
    return outfile;
});

console.log('compiled: ' + outfile.source);

Demo

Why use TypeScript?

Why not?

Static typing does confer some very relevant value.

Typically it does so at the cost of flexibility, but this brings a lot of the benefits to JavaScript in an optional way, which is very powerful.

Resources

Questions...?

/

#