Issue
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);
}
}
Solution
Modifying the constructor argument of base-class (i.e. ShopConfig
) to use a combination of |
operators and latter checking v
like v instanceof ClassName
and typeof v === 'primitiveName'
did the trick:
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);
}
}
Answered By - Top-Master
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.