打字稿 - 拷贝构造

问题描述 投票:0回答:1

是否TypeScript支持拷贝构造函数(像example C++呢)?

如果答案是否定的(或没有),那么什么是初始化我们的基类(这是我们扩展),并从现有实例复制(同基类类型)的最佳实践

Current Code:

目前我们的代码使用我们的基类的手动声明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个回答
1
投票

改性基类(即ShopConfig)的构造器参数使用|运营商和后者检查vv 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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.