TypeScript


Advantages of TS

Common Datatypes

TypeScript: Handbook - Basic Types

Interfaces

Interfaces make sure an Object matches a specific structure. The order of the values does not matter.

interface Food {
    name: string;
    calories: number;
}

function speak(food: Food): void{
  console.log("Our " + food.name + " has " + food.calories + " calories.");
}

var ice_cream = {
  name: "ice cream", 
  calories: 200
}

speak(ice_cream);

TypeScript: Handbook - Interfaces

Classes

class Menu {
  items: Array<string>;
  pages: number;

  constructor(item_list: Array<string>, total_pages: number) {
    this.items = item_list;    
    this.pages = total_pages;
  }

  list(): void {
    console.log("Our menu for today:");
    for(var i=0; i<this.items.length; i++) {
      console.log(this.items[i]);
    }
  }
} 


// Inheritance

class HappyMeal extends Menu {
  constructor(item_list: Array<string>, total_pages: number) {
    super(item_list, total_pages);
  }

  list(): void{
    console.log("Our special menu for children:");
    for(var i=0; i<this.items.length; i++) {
      console.log(this.items[i]);
    }
  }
Note

There are also native js classes, but they do not support static typing, access modifiers and more.

TypeScript: Handbook - Classes

Generics

Using generics instead of any makes sure the type of the input is preserved. With any, everything is converted to any

function genericFunc<T>(argument: T): T[] {    
  var arrayOfT: T[] = [];
  arrayOfT.push(argument);
  return arrayOfT;
}

var arrayFromString = genericFunc<string>("beep");
console.log(arrayFromString[0]);         // "beep"
console.log(typeof arrayFromString[0])   // String

var arrayFromNumber = genericFunc(42);
console.log(arrayFromNumber[0]);         // 42
console.log(typeof arrayFromNumber[0])   // number