如何在Javascript/Typescript中创建基于类的枚举

2024-09-27 19:27:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段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中构建这样一个基于类的枚举是什么语法


Tags: 代码importdataenumjavascriptclassotherprint
3条回答

枚举是一个typescript概念,在here中有文档记录。编写枚举时,typescript正在创建一个与枚举选项匹配的普通js对象,因此可以使用“in”运算符检查提供的值是否是枚举的成员

类型脚本枚举

enum Direction {
  Up,
  Down,
  Left,
  Right,
}

这在javascript中是什么

var Direction = {
  '0': 'Up',
  '1': 'Down',
  '2': 'Left',
  '3': 'Right',
  Up: 0,
  Down: 1,
  Left: 2,
  Right: 3
}

检查某个值是否是枚举的成员可以使用

const foo = "Up";

// Unsafe, but quick and easy.
console.log(foo in Direction); // returns true.
console.log("toString" in Direction); // also returns true.

// Safe.
console.log(Direction.hasOwnProperty(foo)); // returns true.
console.log(Direction.hasOwnProperty(foo)); // returns false.

这就是如何在JS/TS中创建枚举的方法-

const enum OneDBServerPermission {
  RECTANGLE = 0
  CIRCLE = 1
  TRIANGLE = 2
  OTHER = 3
}

如果您想在其他类中使用它,可以使用导出关键字

export const enum OneDBServerPermission {
  RECTANGLE = 0
  CIRCLE = 1
  TRIANGLE = 2
  OTHER = 3
}

TypeScript中没有定义基于类的枚举的特定“语法”。但是这里有一个名为Shape的类的示例,它可以识别四种类型的形状

Shape提供接受参数shapeType的构造函数。如果shapeType不是可识别的类型,create抛出异常

class Shape {
  constructor(public shapeType: number) {
    if (!Shape.types.includes(shapeType)) {
      throw new Error(`Value ${shapeType} is not a valid shape type.`);
    }    
  }

  static readonly rectangle: number = 0;
  static readonly circle: number = 1;
  static readonly triangle: number = 2;
  static readonly other: number = 3;

  static get types(): number[] {
    return [
      Shape.rectangle,
      Shape.circle,
      Shape.triangle,
      Shape.other,  
    ];
  }
}

用法:

const shape1: Shape = new Shape(Shape.triangle);
const isInstanceOf: boolean = shape1 instanceof Shape;
console.log(`Is Shape? ${isInstanceOf}; type is ${shape1.shapeType}`); // Is Shape? true; type is 2

try {
  const shape2: Shape = new Shape(42);
} catch (e) {
  console.log(e.message); // Value 42 is not a valid shape type.
}

有关可能希望从枚举移动到类的原因,请参见C# vs Java Enum (for those new to C#)

相关问题 更多 >

    热门问题