【发布时间】:2016-03-08 03:43:34
【问题描述】:
(这个例子是由 Typescript 写的,但不仅限于 Typescript 案例)
class IMyInterface {
doC:(any) => any;
}
class Common {
commonProperty:any;
doA() {
}
doB() {
}
}
class ClassA extends Common {}
class ClassB extends Common implements IMyInterface {
doC(test:any) {
return true;
}
}
class Factory {
myClass: Common;
doSomething() {
// Property 'doC' does not exist on type 'Common'
this.myClass.doC('test');
}
}
A类和B类是Common类的扩展类,因此在Factory类中可以将myClass类型定义为Common。
但是B类需要实现IMyInterface,Common类不包含。所以Factory类抛出Common类不存在接口方法的错误。
解决这个问题的最佳方法和方法是什么?
[已编辑]
首先,@basarat 非常感谢你,但我还是有点好奇,
如果有更多类实现 IMyInterface 怎么办
class ClassC extends Common implements IMyInterface {
doC(test:any) {
return true;
}
}
class ClassD extends Common implements IMyInterface {
doC(test:any) {
return true;
}
}
class ClassE extends Common implements IMyInterface {
doC(test:any) {
return true;
}
}
在那种情况下,我可以想,我可以在 Common 类中定义 doC() 方法。 但我也想让ClassB、C、D和E必须实现Doc方法。
请给我建议,
【问题讨论】:
-
请参阅我对
class C等案例的回答的更新
标签: oop typescript