TypeScript

Overview

TypeScript is a "super"-set of JavaScript, the language that runs the web. As the name suggests, TypeScript uses a static type system instead of a dynamic one like JavaScript. This helps code readability and maintainability.

Examples

Many of the following examples are taken from learnxinyminutes.com.

// There are 3 basic types in TypeScript
let isDone: boolean = false;
let lines: number = 42;
let name: string = "Anders";

// When it's impossible to know, there is the "Any" type
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;

// Const keyword for constants
const numLivesForCat = 9;
numLivesForCat = 1; // Error

// Collections use typed arrays
let list: number[] = [1, 2, 3];

// For more complex arrays use a generic array type
let matrix: Array<Array<number>> = [[1, 2] [3, 4]];

// Enums
enum Color { Red, Green, Blue };
let c: Color = Color.Green;

// Void for non-returning functions
function bigHorribleAlert(): void {
    alert ("Horrible Alert!");
}

// Functions can accept more than one type
function f6(i: string | number): void {
    console.log("The value was " + i);
}

// Interfaces
interface Person {
    name: string;

    // Optional property
    age?: number

    // Function property
    move(): void;
}
let p: Person = { name: "Bobby", move: () => {} };

// Classes
class Point {
    x: number;

    constructor(x: number, public y: number = 0) {
        this.x = x;
    }

    // Functions in classes
    dist(): number { return Math.sqrt(this.x * this.x + this.y * this.y); }

    // Static members
    static origin = new Point(0, 0);
}
let p1 = new Point(10, 20);
let p1 = new Point(25); // y will be 0