繁体   English   中英

如何在TypeScript中键入类的函数的返回值作为其类的属性的值?

[英]How to type a class' function's return as the value of its class' attribute in TypeScript?

假设我有一个类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

调用is_asbestos方法会给我这个错误。

属性“ is_asbestos”在“产品”类型上不存在。

因此,我如何告诉TypeScript该函数的返回值是product_cls值的实例,后者是一个类。

现在,我可以按照以下方式进行操作,并且可以正常工作,但是在每个函数调用中这样做都是很愚蠢的。

let new_roof = <Roof>roof_factory.build_for_france();
new_roof.is_asbestos();

执行以下操作会给我带来语法错误。

build_for_france(){
    let french_product: this.product_cls = new this.product_cls();
    return french_product;
}

最后,我正在使用Typescript 2.0.10。 我不介意升级TypeScript版本。

您必须使用泛型来指定工厂构造的类型。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM