如何从泛型类型中获取STATIC animalType?

时间:2016-07-14 12:10:09

标签: typescript

鉴于以下示例代码,我想获得T.animalType中泛型,static,animalType的值,如何处理这个?

export class main {

    constructor() {

        var myWorker: worker = new worker();
        myWorker.whatAmI();

    }

}

export class worker extends workerBase<dog> {

}

export class workerBase<T extends animal>
{
    public whatAmI() {
        //output animal type as "dog"
        console.warn("Animal type: " + T.animalType); // <<-- this will NOT work, but this is what I want to achieve
    }
}

export class animal {
    public static animalType: string = "any";
}

export class dog extends animal {
    public static animalType: string = "dog";
}

1 个答案:

答案 0 :(得分:0)

通用类型在运行时不可用,并且类型也不可用,因为javascript没有类型的概念。

例如:

var hasRequiredField = Object.keys(req.body).some(function(key) {
return ['a', 'b', 'c'].indexOf(key) >= 0;
});

if(hasRequiredField) {
} else {

}

编译成:

class A<T> {
    private x: number;

    constructor(x: number) {
        this.x = x;
    }
}

正如你可以看到编译的js中x(var A = (function () { function A(x) { this.x = x; } return A; }()); )的类型不是,number也没有。

你能做的是:

T

code in playground

相关问题