0

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

user2024080
  • 1
  • 14
  • 56
  • 96
  • Interface doesn't carry implementation, only contract – Aleksey L. Nov 03 '21 at 09:11
  • Change interface name and TS will start yelling - impl is wrong https://www.typescriptlang.org/play?#code/MYGwhgzhAECCB2BLAtmE0DeBYAUNf0EADgKbCIkQBchALgE6LwDmA3LgdIgCY3wCuyAEYl60ALzQADOzwFgAe3gQG-YLQX0AFMTIVqdRiwCUmDpwK0AFoggA6XeUoTCpJxHP4Avp+gkwtFoAZvT8iLRUKkbMxlQAbgo82HIW0IrKCiAkdiAKzFoA5P60TMxcMFb+ILQAngXQANTQIWG0xr4+OJ2gkDAACqIQSmYp0PBgyCQ0UaWynDx8giJikjK+6VFqGtrjk9MMpabJqfjWtna7JC6XHb66YADWWsbHJxuZ2bn5Z-aXjdA-Ow8YxzAidTpMWiiIJgYBXACiyCIuRqJBIAEY-AAPKHwbj9QZKAA0cCQqHQGE4vhISJRaIAwgpuFNDLNcN1wFBoIjkQpUVcUMiaSR4LQYDy6RiRpwNqp1Jpnq98L5oODcLgsrQ-LS+WiaBLdVdJPASAB3bk6-nPWQ03n8uzFQpgIhCgogoA – Aleksey L. Nov 03 '21 at 09:13

1 Answers1

1

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.

sam256
  • 1,291
  • 5
  • 29