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

Typescript 如何将泛型参数转换为枚举?,typescript,generics,Typescript,Generics,如何以最小的运行时性能开销将泛型参数转换为枚举 i、 e.如何完成下面的Get,以便MyClass.Get返回eDog interface IAnimal {} class Dog implements IAnimal {} class Cat implements IAnimal {} enum Animals { eDog = 0, eCat = 1 }; class MyClass { static Get<T extends IAnimal>() : Anima

如何以最小的运行时性能开销将泛型参数转换为枚举

i、 e.如何完成下面的Get,以便
MyClass.Get
返回
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 ...?
    }
}
接口IAnimal{}
类Dog实现IAnimal{}
类Cat实现IAnimal{}
枚举动物{eDog=0,eCat=1};
类MyClass{
静态Get():动物{
返回。。。?
}
}

我通常在TypeScript中看到的是:

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

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

...

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

类型参数在编译时被擦除,所以我们不能在运行时使用它们来获取任何信息。我们可以做的是使用构造函数作为参数传递的功能

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

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

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));
或者在类构造函数上使用
开关

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));

枚举和类之间没有关系。所以除了一个开关,你不能用你想要的类做任何事情provide@titian-cernicova dragomir**than(抱歉)您如何比较该类型?是否有一个等价的C#typeof()可以在泛型参数上调用?@TitianCernicova Dragomir您不能在泛型上进行切换。@daw泛型(以及通常与类型相关的任何内容)在编译时丢失,因此您不能在泛型上进行typeof。太好了!lambda类型中的“new”与我不相似,在文档中找不到它,你能解释一下或告诉我在文档中的位置吗?它被称为构造函数签名,它允许你指定一个类构造函数,而不是一个常规函数hmm不能从一个具有泛型参数的函数调用你的Get,例如“CallGet():Animals{return Get(T) }“所以这并不能解决问题-仍然在尝试将类型转换为值。@daw泛型在编译时被删除。要在运行时获取任何内容,需要将构造函数作为参数传递,而不是传递给构造函数。谢谢。如果您能将该注释添加到答案的顶部,我将接受它。