[英]How to type a class' function's return as the value of its class' attribute in TypeScript?
Provided i have a Class Factory
who takes in another class Product
(or its subclass) as an argument and has methods that return instantiated Products will a lot of extra done to them, like so: 假设我有一个类
Factory
,该类Factory
将另一个类Product
(或其子类)作为参数,并且具有返回实例化Products的方法,则将对它们做很多额外的工作,例如:
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
Calling the is_asbestos
method gives me this error. 调用
is_asbestos
方法会给我这个错误。
Property 'is_asbestos' does not exist on type 'Product'.
属性“ is_asbestos”在“产品”类型上不存在。
So, how do i tell TypeScript that the return value of that function is an instance of the value of product_cls
, which is a class. 因此,我如何告诉TypeScript该函数的返回值是
product_cls
值的实例,后者是一个类。
Now, i can do the below way and it works, but doing that at every function call is silly. 现在,我可以按照以下方式进行操作,并且可以正常工作,但是在每个函数调用中这样做都是很愚蠢的。
let new_roof = <Roof>roof_factory.build_for_france();
new_roof.is_asbestos();
Doing the following gives me a syntax error. 执行以下操作会给我带来语法错误。
build_for_france(){
let french_product: this.product_cls = new this.product_cls();
return french_product;
}
Finally, I'm using Typescript 2.0.10. 最后,我正在使用Typescript 2.0.10。 I do not mind upgrading the TypeScript version.
我不介意升级TypeScript版本。
You must use generics to specify which type your factory constructs. 您必须使用泛型来指定工厂构造的类型。
abstract class Product {}
class Wheel extends Product {}
class Roof extends Product {
is_asbestos(){ return false } }
type ProductClass<T> = {new (): T}
class Factory<T extends Product> {
public product_cls: ProductClass<T>;
constructor(product_cls: ProductClass<T>, private regulation_code?: number) {
this.product_cls = product_cls;
}
build_for_france(): T {
return new this.product_cls();
}
build_for_britain(): T {
return new this.product_cls();
}
}
let wheel_factory = new Factory<Wheel>(Wheel);
let roof_factory = new Factory<Roof>(Roof, 123);
let new_roof = roof_factory.build_for_france();
new_roof.is_asbestos(); // ok
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.