【发布时间】:2019-07-03 22:48:09
【问题描述】:
TypeScript 是否支持复制构造函数(如 example C++ 支持)?
如果答案是否定的(或还没有),那么初始化我们的基类(我们扩展)并从现有实例(相同的基类类型)复制的最佳实践是什么。
我试过了,但出错了:
Multiple constructor implementations are not allowed
当前代码:
目前我们的代码使用我们基类的手动声明的copy() 方法,这确实要求基类已经初始化,
但是我们的基类 (ShopConfig) 在其构造函数中有一些相当昂贵的操作,这些操作已经完成了一次,如果在 TypeScript 中实现了复制构造函数概念,则不需要这些操作。
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);
}
}
【问题讨论】:
标签: typescript copy-constructor