TypeScript - 复制构造函数(不允许多个构造函数实现)

TypeScript - Copy-Constructor (Multiple constructor implementations are not allowed)

TypeScript 是否支持复制构造函数(与 example C++ 一样)?

如果答案是否定的(或尚未),那么初始化我们的 base-class(我们扩展的)并从现有实例(相同的 base- class类型)。

我尝试了但出现错误:

Multiple constructor implementations are not allowed

当前代码:

目前我们的代码使用我们的 base-class 手动声明的 copy() 方法,这确实需要 base-class 已经初始化,

但是我们的 base-class (ShopConfig) 在其构造函数中有一些相当昂贵的操作,这些操作已经完成一次,如果 [=12= 中有复制构造函数概念,则不需要] 实施。

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);
  }
}

修改 base-class 的构造函数参数(即 ShopConfig)以使用 | 运算符的组合,然后检查 v 就像 v instanceof ClassName typeof v === 'primitiveName' 成功了:

class ShopConfig {
    public apiKey: string;
    public products: any;

    constructor( v: ShopConfig
            | string | String
            | null
            = 'trial'
    ) {
        if ( ! v) {
            throw new Error('ShopConfig: expected API-Key or existing instance');
        } else if (v instanceof ShopConfig) {
            for (const field in v) {
                if (v.hasOwnProperty(field)) {
                    this[field] = v[field];
                }
            }
        } else if (typeof v === 'string' || v instanceof String) {
            this.apiKey = v.toString();
            // Fetch list of products from local Data-Base
            this.products = expensiveDataBaseQuery();
        }
    }
}

class ShopManager extends ShopConfig {

    constructor(config: ShopConfig) {
        super(config);
        console.log('ShopManager configurations:', config);
    }
}