Home > other >  extending multiple class with interface not works
extending multiple class with interface not works

Time:11-03

I am trying to use multiple class by extending in interface. using typescript, but getting this error:

[ERR]: employee.eat is not a function

here is my try:

class Animal {
    species: string;
    id: number = 0;
    constructor(species: string) {
        this.species = species
    }
    eat(fruit:string):void{
        console.log('eating is healty'   fruit)
    }
}
class Person {
    name: string;
    id: number = 0;
    constructor(name: string) {
        this.name = name
    }
    speak(){
        console.log(this.name   this.id);
    }
}
interface Employee extends Person, Animal {    
    employeeCode: string;
}
class Employee implements Employee {
    constructor(){
    
     }
}

let employee: Employee = new Employee();
employee.eat('apple');

Live Demo

CodePudding user response:

Multiple class inheritance is not, strictly speaking, possible in Typescript. Your example is fooling the compiler because you've named your interface the same name as the class, but at the end of the day, an interface of the type you've written will only specify the type of the class, not its implementation. In other words, you'd still have to write out the implementation in your Employee class that matches both Animal and Person.

That said, if what you want is to inherit functionality defined in multiple classes without having them inherit from one another, you can achieve this using the "mixin" pattern described in the Typescript documentation and this SO post.

  • Related