Typescript basics

Typescript basics

1. Install + compile

  1. npm install -g typescript
  2. tsc "file".ts

2. The type system + basic types

  1. Number
    var isWinter : boolean = false;
    
  2. String
    var name : string = "bran";
    
  3. Boolean
    var count : number = 5;
    
  4. Array
    var names : any[] = ["jon", "Rickon", "Arya", 5];
    

    3. Interfaces

    An interface defines the syntax that any entity must adhere to.
interface IPerson { 
   firstName:string, 
   lastName:string, 
   sayHi: ()=>string 
} 

var customer:IPerson = { 
   firstName:"Ajay",
   lastName:"Laddha", 
   sayHi: ():string =>{return "Hi"} 
}

4. Classes

Classes are templates for Objects.

class Greeter {
  greeting: string;

  constructor(message: string) {
    this.greeting = message;
  }

  greet() {
    return "Hello, " + this.greeting;
  }
}

let greeter = new Greeter("world");

5. Inheritance

A class can reuse the properties and methods of another class. This is called inheritance in TypeScript.

class Person {
    constructor(private firstName: string, private lastName: string) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    getFullName(): string {
        return `${this.firstName} ${this.lastName}`;
    }
    describe(): string {
        return `This is ${this.firstName} ${this.lastName}.`;
    }
}