type inheritance typescript code example

Example 1: typescript class interface

interface IPerson {
  name: string
  age: number
  hobby?: string[]
}

class Person implements IPerson {
  name: string
  age: number
  hobby?: string[]

  constructor(name: string, age: number, hobby: string[]) {
    this.name = name
    this.age = age
    this.hobby = hobby
  }
}

const output = new Person('john doe', 23, ['swimming', 'traveling', 'badminton'])
console.log(output)

Example 2: classes in typescript

class Info {
  private name: string ;
  constructor(n:string){
    this.name = n ;
  };
  describe(){
    console.log(`Your name is  ${this.name}`);
  }
}

const a = new Info('joyous');
a.describe();

Example 3: class inheritance in typescript

// Parent class
class Info {
  protected name: string ;
  constructor(n:string){
    this.name = n ;
  };
  describe(){
    console.log(`Your name is  ${this.name}`);
  }
}

//inherited class (you can overwrite methods of parent class, super is used to
// connect to the parent parameter(s) . )

class Detail extends Info{
  constructor(name:string, public age:number){
    super(name);
  }
  findAge(){
      console.log(`${this.name} age is ${this.age}`)
  }
}

const b = new Detail('jank', 23);
b.describe();
b.findAge();