I have a lot of similar classes that I'd like to initialize with the following syntax:
class A {
b: number = 1
constructor(initializer?: Partial<A>) {
Object.assign(this, initializer)
}
}
new A({b: 2})
I think that being able to get initialized by such means is a generic behaviour and so I'd like to isolate this logic to avoid repeating myself in douzens of files. I tried this:
class Initializable<T> {
constructor(initializer?: Partial<T>) {
Object.assign(this, initializer)
}
}
class A extends Initializable<A> {
b: number = 1
}
new A({b: 2})
This compiles but doesn't work because the implicit super()
goes first so b
gets 2
as wanted but then gets 1
.
Does TypeScript offers a type-safe solution to get this behaviour in all my classes?