onsa
2/11/2017 - 8:29 PM

Types in TypeScript

Types in TypeScript

//  interfaces are named js objects
interface Name {
  firstName: string;
  lastName: string;
}

//  classes are also named js objects
class Person {
  public fullName: string;      //  have properties but with visibility
  //  have constructors as well
  constructor(private name: Name) {     //  scoped constructor parameters don't need to be declared explicitly
      this.name = name;
      this.fullName = this.name.firstName + " " + this.name.lastName;
  }

  //  have methods
  public introduce() {
    let introduction = 'Hi, my name is ' + this.name.firstName + '.';
    return introduction;
  }

}

//  classes can be extended
class Resident extends Person {
  public address;                               //  only new/overridden properties/methods need to be explicit
  constructor(name: Name, address: string) {
    super(name);                                //  parent constructor called with super
    this.address = address;
  }

  public introduce() {
    //  parent method called with super.method()
    let introduction = super.introduce() + ' And my address is: ' + this.address;
    return introduction;
  }
  
}