Does TypeScript
support copy-constructor (like for example C++ does)?
When the answer is no (or not yet), then what is the best practice to initialize our base-class (which we extend), and copy from an existing instance (of the same base-class type).
I tried but got error:
Multiple constructor implementations are not allowed
Current Code:
Currently our code uses the manually declared copy()
method of our base-class which does require the base-class to be already initialized,
But our base-class (ShopConfig) has some rather expensive operations in its constructor, which are already done once, and would not be required if there was a copy-constructor concept in TypeScript
implemented.
class ShopConfig {
public apiKey: string;
public products: any;
constructor(apiKey: string = 'trial') {
this.apiKey = apiKey;
//Fetch list of products from local Data-Base
this.products = expensiveDataBaseQuery();
}
protected copy(other: ShopConfig) {
for (const field in other) {
if (other.hasOwnProperty(field)) {
this[field] = other[field];
}
}
}
}
class ShopManager extends ShopConfig {
constructor(config: ShopConfig) {
super();
super.copy(config);
console.log('ShopManager configurations:', config);
}
}