如何将泛型参数转换为枚举?

时间:2018-02-20 20:23:40

标签: typescript generics

如何将通用参数转换为具有最小运行时性能开销的枚举?

即。如何完成下面的获取,MyClass.Get<Dog>返回eDog

interface IAnimal {}
class Dog implements IAnimal {}
class Cat implements IAnimal {}

enum Animals { eDog = 0, eCat = 1 }; 

class MyClass {
    static Get<T extends IAnimal>() : Animals {
        return ...?
    }
}

2 个答案:

答案 0 :(得分:2)

类型参数在编译时被删除,因此我们无法在运行时使用它们来获取任何信息。我们可以做的是使用将构造函数作为参数传递的能力。

使用构造函数作为参数,您可以执行以下两项操作之一:

您可以在类上定义静态字段并在函数中使用

function Get(cls: { new (...args: any[]): IAnimal, type: Animals}) : Animals {
    return cls.type;
}
//Usage
class Dog implements IAnimal { static type: Animals.eCat}
class Cat implements IAnimal { static type: Animals.eCat}
console.log(Get(Dog));
console.log(Get(Cat));

或者使用switch类构造函数:

function Get(cls:  new (...args: any[]) => IAnimal, ) : Animals {
    switch(cls)
    {
        case Dog: return Animals.eDog;
        case Cat: return Animals.eCat;
    }
}
//Usage
console.log(Get(Dog));
console.log(Get(Cat));

答案 1 :(得分:1)

我在TypeScript中经常看到的是:

interface IAnimal { type: Animals; }
class Dog implements IAnimal { type: eDog; }
class Cat implements IAnimal { type: eCat; }

enum Animals { eDog = 0, eCat = 1 }; 

...

注意:我没有检查此代码是否编译。