【发布时间】:2014-11-27 02:26:23
【问题描述】:
假设我有一个这样的“基础”类:
class CcDefinition {
// Some properties here
constructor (json: string);
constructor (someVar: number, someOtherVar: string);
constructor (jsonOrSomeVar: any, someOtherVar?: string) {
if (typeof jsonOrSomeVar=== "string") {
// some JSON wrangling code here
} else {
// assign someVar and someOtherVar to the properties
}
}
}
我希望能够扩展这个基类,同时仍然支持构造函数重载。例如:
class CcDerived extends CcDefinition {
// Some additional properties here
constructor (json: string);
constructor (someVar: boolean, someOtherVar: number, someAdditionalVar: string);
constructor (jsonOrSomeVar: any, someOtherVar?: number, someAdditionalVar?: string) {
if (typeof jsonOrSomeVar=== "string") {
super.constructFromJson(jsonOrSomeVar);
} else {
super.constructFromDef(someOtherVar, someAdditionalVar);
// assign someVar to the additional properties of this derived class
}
}
}
问题在于 Typescript 要求“super”关键字在构造函数实现中首先出现(字面意思)。具体构建错误信息为:
“当类包含初始化属性或具有参数属性时,'super'调用必须是构造函数中的第一条语句。”
但是,我需要根据提供给扩展(派生)类的内容来确定将哪些参数传递给“超级”(即使用不同的构造函数重载)。您应该在这里假设派生类的构造函数重载可能与超级类的重载非常不同。
对于我想要实现的目标有解决方法吗?
【问题讨论】:
-
有人提出同样的问题(没有解决方案):[typescript.codeplex.com/workitem/91]
标签: inheritance constructor typescript overloading extends