我有一段python代码,我正试图将其转换为Javascript/Typescript
import enum
class Shape(enum.Enum):
RECTANGLE = 0
CIRCLE = 1
TRIANGLE = 2
OTHER = 3
print(isinstance(data, Shape))
在Typescript中,我可以使用枚举,但这不是我要找的。我需要这样做的能力:
const data = new Shape().RECTANGLE;
console.log(data instanceof Shape); // should return true
这在使用枚举或对象时是不可能的
编辑:在Typescript中构建这样一个基于类的枚举是什么语法
枚举是一个typescript概念,在here中有文档记录。编写枚举时,typescript正在创建一个与枚举选项匹配的普通js对象,因此可以使用“in”运算符检查提供的值是否是枚举的成员
类型脚本枚举
这在javascript中是什么
检查某个值是否是枚举的成员可以使用
这就是如何在JS/TS中创建枚举的方法-
如果您想在其他类中使用它,可以使用导出关键字
TypeScript中没有定义基于类的枚举的特定“语法”。但是这里有一个名为
Shape
的类的示例,它可以识别四种类型的形状Shape
提供接受参数shapeType
的构造函数。如果shapeType
不是可识别的类型,create
抛出异常用法:
有关可能希望从枚举移动到类的原因,请参见C# vs Java Enum (for those new to C#)
相关问题 更多 >
编程相关推荐