I have multiple classes that I would like to initialize using the following syntax:
class A {
b: number = 1
constructor(initializer?: Partial<A>) {
Object.assign(this, initializer)
}
}
new A({b: 2})
It seems to me that this initialization behavior is a common pattern and I want to centralize this logic to avoid duplication in many files. I attempted the following approach:
class Initializable<T> {
constructor(initializer?: Partial<T>) {
Object.assign(this, initializer)
}
}
class A extends Initializable<A> {
b: number = 1
}
new A({b: 2})
This code compiles successfully but does not work as expected because the implicit super()
call overrides the initialized value of b
. Is there a type-safe solution in TypeScript to achieve this shared behavior in all my classes?