Imagine having a Class Factory
that accepts another class Product
(or its subclass) as an argument and has methods to return instantiated Products with additional modifications. Here is an example:
abstract class Product {}
class Wheel extends Product {}
class Roof extends Product {
is_asbestos(){ return false } }
type ProductClass = {new (): Product}
class Factory {
public product_cls: ProductClass;
constructor(product_cls: ProductClass, private regulation_code?: number) {
this.product_cls = product_cls;
}
build_for_france(){
return new this.product_cls();
}
build_for_britain(){
return new this.product_cls();
}
}
let wheel_factory = new Factory(Wheel);
let roof_factory = new Factory(Roof, 123);
let new_roof = roof_factory.build_for_france();
new_roof.is_asbestos(); // error
An error occurs when trying to call the is_asbestos
method.
The property 'is_asbestos' does not exist on the type 'Product'.
How can TypeScript be informed that the return value of that function is an instance of the product_cls
class?
The workaround below works, but it might not be practical to do it for every function call.
let new_roof = <Roof>roof_factory.build_for_france();
new_roof.is_asbestos();
If attempted in the following manner, a syntax error is encountered.
build_for_france(){
let french_product: this.product_cls = new this.product_cls();
return french_product;
}
Finally, the version of TypeScript being used is 2.0.10, and an upgrade is possible if necessary.