This restriction only applies if you initialized the properties of an element in a derived class, so the first workaround is to simply declare these properties and then initialize them in the constructor of the derived class.
In other words, you can change:
class CcDerived extends CcDefinition { y = 10; constructor (json: string); constructor (someVar: boolean, someOtherVar: number, someAdditionalVar: string); constructor (jsonOrSomeVar: any, someOtherVar?: number, someAdditionalVar?: string) { if (typeof jsonOrSomeVar=== "string") { super(jsonOrSomeVar); } else { super(someOtherVar, someAdditionalVar); } } }
:
class CcDerived extends CcDefinition { // Some additional properties here y: number; constructor (json: string); constructor (someVar: boolean, someOtherVar: number, someAdditionalVar: string); constructor (jsonOrSomeVar: any, someOtherVar?: number, someAdditionalVar?: string) { this.y = 10; if (typeof jsonOrSomeVar=== "string") { super(jsonOrSomeVar); } else { super(someOtherVar, someAdditionalVar); } } }
Please note that the initialization order here is approximately the same as in other OOP languages, and you need to be careful not to call virtual methods from constructors, etc.
If this is too annoying, note that the limitation is simply that the first statement is a super call. You can often reorganize a super call:
class CcDerived extends CcDefinition { constructor (json: string); constructor (someVar: boolean, someOtherVar: number, someAdditionalVar: string); constructor (jsonOrSomeVar: any, someOtherVar?: number, someAdditionalVar?: string) { super( typeof jsonOrSomeVar === 'string' ? jsonOrSomeVar : someOtherVar, typeof jsonOrSomeVar === 'string' ? undefined : someAdditionalVar); } }
Not the most beautiful, but it is at least semantically equivalent. This assumes your base class constructor checks undefined (instead of arguments.length ) to determine which overload has been called.
Ryan cavanaugh
source share