'Typescript - inherit duplicated constructor in all derived classes using generics
I have some classes that have identical constructor (partial field assignment). I don't want to write a lot of duplicated constructor so I come up with:
class Base<T> {
constructor(properties: Partial<T> = {}) {
Object.assign(this, properties);
}
}
class Child {
data: number[] = []
ownMethod() {
// ...
}
}
var test = new Base<Child>({data: [1,2,3]}); // Base: {"data": [1,2,3]}
This works, but the instances created are all Base instead of Child. Is there a way to make each derived class construct itself instead of Base?
class Child extends Base<Child> {
data: number[] = []
ownMethod() {
// ...
}
}
var test = new Child({data: [1,2,3]}); // Child: {"data": []}
This does not work.
class Child extends Base<Child> {
data!: number[]
isOpen: boolean
ownMethod() {
// ...
}
}
var test = new Child({data: [1,2,3]}); // Child: {"data": [1,2,3]}
This works partially, that Partial does not make sense as if you are not specifying a field it will not be in the object (e.g. isOpen)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
