【问题标题】:TypeScript - Copy-Constructor (Multiple constructor implementations are not allowed)TypeScript - Copy-Constructor(不允许多个构造函数实现)
【发布时间】: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


    【解决方案1】:

    修改基类的构造函数参数(即ShopConfig)以使用| 运算符的组合,然后检查v,如v instanceof ClassNametypeof 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-24
      • 2019-02-21
      • 2017-04-23
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 2019-10-27
      相关资源
      最近更新 更多