TypeScript

Junghoo Cho

cho@cs.ucla.edu

TypeScript

Example

Transpilation

Static Type Checking

Why Static Type Checking?

Type Annotations

let a: number = 1;
let b: string = "A";
let c: boolean = true;
let d: number[] = [1, 2];                           // array
let e: [number, string] = [1, "A"];                 // tuple
let f: (number | string) = 1; // or "A"             // union
let g: any = "A";  // or 1, [1, 2], ...             // any
let h: void = undefined; // or null                 // void
let i: never; // nothing can be assigned            // never

let j: {x: number, y: string} = {x:1, y:"A"};       // object

function hello(name: string): void {                // function
    console.log(`Hello, ${name}!`);  
}
let k: (x: string) => void = hello;                 // function object

Type Compatibility: Basic Types

Type Compatibility: Object Types

Type Compatibility: Object Types

Type Conversion

Enum Type

Functions (1)

Functions (2)

Function: Rest Parameters

Classes

// JavaScript
class Point {
    constructor(x, y)
    {
        this.x = x;
        this.y = y;
    }
}
// TypeScript
class Point {
    private x: number;
    public  y: number;
    constructor (x: number, 
                 y: number)
    {
        this.x = x;
        this.y = y;
    }
}

Class Constructor Shorthand

class Point {
    private x: number;
    public  y: number;
    constructor (x: number, 
                 y: number)
    {
        this.x = x;
        this.y = y;
    }
}
class Point {
    constructor (private x: number, 
                 public  y: number) 
    {}
}

Non-Null Assertion Operator

Interfaces (1)

Interfaces (2)

Generics

Decorators

Getter and Setter (ECMAScript 2015)

class Dot {
    _x = 0;
    set x(v) { this._x = v;  }               // setter
    get norm() { return Math.abs(this._x); } // getter
};

let p = new Dot();
console.log("p.norm = " + p.norm);      // no parenthesis!
console.log("Before: p._x = " + p._x);
p.x = 20;                               // not a function call!
console.log("After:  p._x = " + p._x);

What We Learned

References