【发布时间】:2016-10-27 18:42:44
【问题描述】:
我怎样才能在打字稿中实现类似于这种模式的东西?
class A {
Init(param1: number) {
// some code
}
}
class B extends A {
Init(param1: number, param2: string) {
// some more code
}
}
上面截取的代码看起来应该可以工作,但是仔细检查 How Typescript function overloading works 后发现抛出错误是有道理的:
TS2415: 'Class 'B' incorrectly extends base class 'A'.
Types of property 'Init' are incompatible.
我知道构造函数允许这种行为,但我不能在这里使用构造函数,因为这些对象是为了提高内存效率而池化的。
我可以在 A 类中提供另一个 Init() 的定义:
class A {
Init(param1: number, param2: string): void;
Init(param1: number) {
// some code
}
}
但这并不理想,因为现在基类需要了解其所有派生类。
第三种选择是重命名 B 类中的 Init 方法,但这不仅会非常丑陋和令人困惑,而且会在基类中暴露 Init() 方法,这会导致难以检测的错误基类 Init() 被错误调用。
有没有什么方法可以实现这种模式而不存在上述方法的缺陷?
【问题讨论】:
标签: inheritance typescript overloading