Inheritance in TypeScript


Inheritance in TypeScript

1. extends

extends is an easy concept. omitted here.

2. implements

extends is the child of a class but implements is the shape of a class.

In typescript (and some other OO languages) you have classes and interfaces.

An interface has no implementation, it’s just a “contract” of what members/method this type has.

For example:

interface Animal{
  age: number;
  legs: number;
  name: string;
}

Instances who implement this Aminal interface must have two members of type number: age and legs, and one member of type string name. The interface doesn’t implement any of those.

Classes are the implementations:

class Animal{
  age: number;
  legs: number;
  name: string;

  constructor(age:number,legs:number,name:string){
    this.age = age;
    this.legs = legs;
    this.name = name;
  }
}

class Dog implements Animal {
  age: number;
  legs: number;
  name: string;

  constructor(age:number,legs:number,name:string){
    this.age = age;
    this.legs = legs;
    this.name = name;
  }

  woof():string {
    return "Woof! I am a dog!"
  }
}

class Cat extends Animal {
  constructor(age:number,legs:number,name:string){
    super(age,legs,name);
  }
  neow():string {
    return "meow! I am a cat! "
  }
}

In the above example we treat Animal class once as a class when we extend it and once as an interface when we implement it.