My goal is to create a parent class that allows children to generate new instances of the same child type. When I specify the number of parameters, everything functions correctly:
abstract class AClass {
protected sameTypeWithSingle (
x: any
): this {
const self = this as this & {
constructor: { new (x: any) }
}
return new self.constructor (x)
}
protected sameTypeWithDouble (
a: any, b: any
): this {
const self = this as this & {
constructor: { new (a: any, b: any) }
}
return new self.constructor (a, b)
}
}
However, when I attempt to accept any number of parameters in order to match any child constructor signature, it does not work (shown with TypeScript error comments):
abstract class AClass {
protected sameTypeWith (
...args: any[]
): this {
const self = this as this & {
constructor: { new (...args: any[]) }
}
return new self.constructor (...args)
// [ts] Cannot use 'new' with an expression whose type
// lacks a call or construct signature.
}
}
I am puzzled as to why it breaks - it works with 2 parameters but not with any? Is there a way to achieve my intended functionality?
Thank you for your help,
Seb