Typescript Tutorial

Basic Types

Boolean

let isDone: boolean = false;

Number

let six: number = 6;
let hex: number = 0xff;
let binary: number = 0b1010;
let octal: number = 0o74;

String

let color: string = "blue";
color = 'red';

let fullName: string = 'Bob';
let age: number = 37;
let sentence: string = `Hello, my name is ${fullName}. I'm ${age} years old.`;

Array

let list: number[] = [1, 2, 3];

Tuple

let x: [string, number];
x = ["hello", 10]; // OK
x = [10, "hello"]; // Error

x[0].substr(1); // OK
x[1].substr(1); // Error

let point: [number, number] = [1, 2];

Any

let a: any = 4;
a.toFixed(); // OK
a.substr(1); // OK

Void

function alertUser(): void {
    alert("This is warning");
}

let unusable: void = undefined;

Null and Undefined

let u: undefined = undefined;
let n: null = null;

let x: number = null;
let s: string = undefined;

Function Return Type

function isGood(d: any): boolean {
    return d === 'good';
}

Core Type

let b: Boolean = true;
let s: String = 'abc';
let n: Number = 123;
let a: Array<any> = [0, '1', true];
let f: Function = function() {};
let d: Date = new Date();
let o: Object = {};

Type assertions

let someValue: Object = "this is a string";

let strLength: number = (<string>someValue).length;
// OR
let strLength: number = (someValue as string).length;

Type Inference

let x = 3; // x: number

function count(arr: any[]) { // returns: number
    return arr.length;
}

window.onclick = function(evt) {
    // evt: MouseEvent
    // this: Window
    // ...
}

Complex Types

Object Shape

let point: {x: number; y: number};
point = {x: 10, y: 20}; // OK
point = {x: 20}; // Error
point = {x: '1', y: '2'}; // Error

Optional Parameters and Properties

function add(x: number, y: number, z?: number): number {
    // ...
}
add(1, 2, 3); // OK
add(1, 2); // OK
add(1); // Error

let response: {
    code: number;
    msg: string;
    data?: any
};
response = {
    code: 404,
    msg: 'not found'
}; // OK

Function Types

function add(x: number, y: number): number {
    return x + y;
}

let mathOp: (x: number, y: number) => number;

mathOp = add;

mathOp = (x, y) => x * y;

Union Types

let x: number | string;
x = '20'; // OK
x = 1; // OK
x.toFixed(); // Error

function someFun(p: number | boolean) {
    // ...
}
someFun(1); // OK
someFun(true); // OK
someFun('3'); // Error

Type Guards

function almightyFunc(x: number | string | any[] | Date) {
    if (typeof x === 'number') {

    } else if (typeof x === 'string') {

    } else if (Array.isArray(x)) {

    } else if (x instanceof Date) {

    }
}

Type Alias

type Name = string;

type Point = {x: number; y: number};
let p: Point = {x: 1, y: 2};

type WithLength = string | any[];
function tellLength(x: WithLength) {
    return x.length;
}

Interfaces

Properties and Methods

interface Point {
    x: number;
    y: number;
    z?: number;
}
let p: Point = {x: 1, y: 2};


interface User {
    readonly name: string;
    address: string;
}
function checkName(u: User) {
    u.address = 'here'; // OK
    if (u.name = 'Bob') { // Error
        // ...
    }
}

interface Shape {
    getArea(): number;
}
function calcCost(s: Shape): number {
    return s.getArea() * 100;
}

interface Observer {
    next?: (value: any) => void;
    complete?: () => void;
    error?: (reaseon: any) => void;
}
function registerObserver(o: Observer) {
    // ...
}

Function Types

interface BinaryMathFunc {
    (a: number, b: number): number;
}

let f: BinaryMathFunc = (x, y) => x + y;
f = function(m, n) { return m * n };

Indexable Types

interface StringArray {
    [index: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Fred"];
let l = myArray.length; // Error

interface MapLike {
    [key: string]: any;
}
let m: MapLike = {};
m['x'] = 10;
m['y'] = 'good';

Hybrid Types

interface JQueryMock {
    (selector: string): any;
    isReady: boolean;
    ajax(options: {[key: string]: any}): any;
}

let $$: JQueryMock;
/*
 * $$ = ...
 */

$$('.btn');
$$.isReady;
$$.ajax({url: 'test'});

interface StorageMock {
    getItem(key: string): string;
    setItem(key: string, data: string): void;
    length: number;
    [key: string]: any;
}
let myLocalStorage: StorageMock;
/*
 * myLocalStorage = ...
 */
 myLocalStorage.setItem('x', 'abcd');
 let abcd = myLocalStorage['abcd'];

Extending

interface Shape {
    color: string;
}

interface Square extends Shape {
    sideLength: number;
}

let sq: Square = {
    color: 'blue',
    sideLength: 10
};

Class Implementing an Interface

interface HasArea {
    getArea(): number;
}

class Circle implements HasArea {
    radius: number = 10;

    getArea() {
        return Math.PI * this.radius * this.radius;
    }
}

function calcCost(a: HasArea): number {
    return a.getArea() * 100;
}

let cost = calcCost(new Circle());

Classes

Public, Private, Protected, Readonly

class ParentClass {
    public x: string;
    protected y: string;
    private z: string;
    readonly r: string;
}

class ChildClass extends ParentClass {
    test() {
        this.x;
        this.y;
        this.z; // Error
    }
}

let p = new ParentClass();
p.x;
p.y; // Error
p.z; // Error
p.r = 's'; // Error

Parameter Properties

class SomeClass {
    constructor(
        public a: string,
        protected b: string,
        private c: string,
        readonly d: string
    ) { }
}

Advanced Topic

Generics

let arrayOfString: Array<string> = [];
arrayOfString.push('123'); // OK
arrayOfString.push(456); // Error
arrayOfString.forEach((value) => {
    console.log(value.toFixed()); // Error
});

let promiseOfNumber: Promise<number> = new Promise((resolve, reject) => {
    resolve('123'); // Error
});
promiseOfNumber.then((value) => {
    value.substr(0, 1); // Error
});

Third Party Library Typings

Install typings file

npm install @types/jquery

Write your own

// my-utils.d.ts
declare module "my-utils" {
    export function repeat(n: number, fn: (i: number) => void): void;
}

// test.ts
import { repeat } from "my-utils";

repeat(10, (i) => {
    // ...
});