TypeScript接口继承多个类后调用方法报not a function如何解决
错误原因
- TypeScript中接口继承类时,仅会继承类的成员类型定义,不会继承任何实际运行时的实现逻辑
- 你自定义的
Employee类虽然声明了实现同时继承Person、Animal的Employee接口,但没有手动实现eat、speak等方法,也没有将两个父类的原型方法混入到Employee类中,运行时自然找不到对应方法抛出错误。
解决方案:使用Mixin实现多继承
TypeScript官方推荐通过混入(Mixin)模式实现类似多继承的能力,实现代码如下:
class Animal { species: string; id: number = 0; constructor(species: string) { this.species = species } eat(fruit:string):void{ console.log('eating is healthy ' + fruit) } } class Person { name: string; id: number = 0; constructor(name: string) { this.name = name } speak(){ console.log(this.name + this.id); } } // 定义Employee接口合并两个父类的类型 interface Employee extends Person, Animal { employeeCode: string; } // 实现Employee类,只写自身独有的属性和方法 class Employee { employeeCode: string = ''; constructor(name: string, species: string, code: string) { // 手动调用两个父类的构造函数初始化属性 Object.assign(this, new Person(name), new Animal(species)); this.employeeCode = code; } } // 混入辅助函数,把父类的原型方法复制到子类原型上 function applyMixins(derivedCtor: any, constructors: any[]) { constructors.forEach((baseCtor) => { Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => { Object.defineProperty( derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name) || Object.create(null) ); }); }); } // 执行混入,将Person和Animal的方法混入到Employee applyMixins(Employee, [Person, Animal]); // 测试运行 let employee: Employee = new Employee('张三', '智人', 'E001'); employee.eat('apple'); // 正常输出 eating is healthy apple employee.speak(); // 正常输出 张三0
内容的提问来源于stack exchange,提问作者user2024080
相关产品推荐
相关产品推荐

