Typescript Fundamentals

Why Typescript?

  • Optional type annotations
  • Static analysis support for the IDE
  • Code organization benefits

Angular2 and Typescript

 

Angular2 is in Typescript/Dart/ES6

 

A2 is written in TS

 

It is recommended to use TS when developing in A2

Access modifiers

Everything in a class is public if not specified. Everything in a module is private unless export keyword is used.

Hello TS

Types

Basic types

  • number
  • boolean
  • string
  • array
  • tuple
  • any

Variable Types

//typescript

let age:number = 5;
let name: boolean = true;
let address: string = 'neverland';
let numbers: number [] = [1,2,3,4];
let counting: Array<number> [] = [1,2,3,4];
let tuple: [number, string] = [1, 'batman'];
let various: any[] = [1, true, 'wayne', [false, 9]];
enum Color {Red, Green, Blue};

Type Inference

//typescript

let age = 5; //inferred as a number
let name = true; //inferred as a boolean
let address; //inferred as any

let person;
person = 'Wiley ol`fox'; //inferred as any

Typescript can infer types if the variables are not annotated

Object Types

//typescript

let hero = {
    name: 'Johnny Quest'
}; //inferred as an Object with a 
   //property name being a string

let zero: Object = {
    name: 'Major'
}; //will be an Object without any 
   //property annotation *

*This is where interfaces would kick in

Function Types

//typescript

//inferred as a type Function
//a, b and return type is any
let add = (a, b) => a + b;


//type Function
//a, b and return type is number
let add: Function = (a: number, b: number) => a + b;

//type Function
//a, b and return type is number
let add: Function = (a: number, b: number): number => a + b;

Superhero Nursery

Interfaces

Interface is a contract that binds an object or class for the properties it can contain

Object Interfaces

//typescript

interface IPlayer {
    name: string,
    age: number,
    retired?: boolean
}

let brainLara: IPlayer = {
    name: 'Brian Lara', 
    age: 45, 
    retired: true
};

Function Interfaces

//typescript

interface ISum {
    (a: number, b: number): number
}

let add: ISum = (a, b) => a + b;

Class Interfaces

//typescript

interface ICar {
    make: number,
    manufacturer: string,
    color?: string,
    running(): boolean
}

Class Interfaces

//typescript

class Toyota implements ICar {
	make: number;
	manufacturer: string;
	
	constructor(make: number, manufacturer: string){
		this.make = make;
		this.manufacturer = manufacturer;
	}
	
	running(){
		return true;
	}
}

Interfaces

Decorators

Typescript Fundamentals

By Mohammad Umair Khan

Typescript Fundamentals

  • 1,023