Typescript

Superset of javascript

Strongly typed

Compiling Files

// this will produce a js file which can even be run on internet explorer
tsc myfile.ts

or

// this will produce js compatile with ES2015
tsc myfile.ts --target ES2015

// if you want to run on Nodejs
tsc myfile.ts --target ES2015 --module commonjs

// add watch flag to watch for changes
tsc myfile.ts --target ES2015 --watch

create a tsconfig.json to save the above configurations

Variables

let x: number;
x = 100;

let y; // y is now of type any
y = 45
y = "aaaaa"

const z = 100;

types available in typescript are: number, boolean, string, any

Arrays

let x: number[] = [1, 2, 3]

Objects

let cc: {
    houseNumber: number;
    streetName: string;
}

cc = {
    streetNumber: 1232,
    streetName: "Street name here"
}

Optional operator -

let dd: {
    houseNumber: number;
    streetName?: string;
}

dd = {
    houseNumber: 343
}

Interface

if we want to re-use the type declared above in object, we can create an interface

interface Address {
    houseNumber: number;
    streetName?: string;
}

let ee: Address = { houseNumber: 13 }

basically interface allows us to create a custom type which we can use for typechecking

interface Person {
    firstName: string,
    lastName: string
}

function fullName(person: Person) {
    console.log(`${person.firstName} ${person.lastName}`)
}

a property in an interface by optional, e.g. -

interface Person {
    firstName: string,
    lastName?: string
}

Functions

function add(num1: number, num2: number): number {
return num1 + num2
}

function sendEmail(to: HasEmail): { recipient: string; body: string } {
return {
recipient: `${to.name} <${to.email}>`,
body: "You're pre-qualified for a loan!"
};
}

optional parameters -

function add(num1: number, num2?: number): number {

}

default parameters -

function add(num1: number, num2: number = 10): number {

}

Classes

class Employee {
    employeeName: string

    constructor(name: string) {
        this.employeeName = string
    }

    greet() {
        console.log(`good morning ${this.employeeName}`)
    }
}

let emp1 = new Employee('Arpit')
console.log(emp1.employeeName)
emp1.greet()

Inheritance -

class Manager extends Employee {
    constructor (managerName: string) {
        super(managerName) // calls Parent class constructor
    }

}

various access modifiers are also available for classes to set accessibility of its variables and methods - public, private, protected.