java - 如何将 Java 枚举转换为 Typescript 枚举

标签 java typescript enums

我在 Java 中设置了一个枚举,如下所示:

public enum ObjectType implements Serializable{

    TABLE(0,"TABLE"),
    VIEW(1,"VIEW");

    private int objectType;
    private String description; 
    private String sqlType;

    ObjectType(int objectType, String description, String sqlType) {
        this.objectType = objectType;
        this.description = description;
        this.sqlType = sqlType;
    }
}

我想设置一个等效的 Typescript Enum,我已经这样做了:

export enum ObjectType {
    TABLE,
    VIEW
}

export namespace ObjectType {

    export function getType(description : string): ObjectType {
        if(description.toUpperCase() === "TABLE") {
            return ObjectType.TABLE;
        } else if(description.toUpperCase() === "VIEW") {
            return ObjectType.VIEW;
        } else {
            return null;
        }
    }

    export function getObjectType(objectType: ObjectType): string {
        switch(objectType) {
            case ObjectType.TABLE:
                return "TABLE";
            case ObjectType.VIEW:
                return "VIEW";
        }
    }
}

我的问题是,我可以创建一个在 Typescript 中也有描述和 sqlType 的构造函数吗?

最佳答案

我不完全确定你是否可以使用 typescript 枚举来做到这一点,但是沿着这些思路应该可以工作:

class MyEnum{

  public static readonly ONE=new MyEnum(1, "Single-Digit");
  public static readonly TWO=new MyEnum(200, "Multi-Digit");

  public readonly index: number
  public readonly type: string

  private constructor(index:number, type: string){
    this.index=index;
    this.type=type;
  }
}

据我所知, typescript 枚举基本上转换为数字,所以这可能是唯一的方法。

关于java - 如何将 Java 枚举转换为 Typescript 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44553838/

相关文章:

objective-c - 获取 NS_ENUM 项目数量的优雅方式

java - 这个java程序是如何工作的?

java - 为什么 getHeaderNames 在 HttpServletRequest 中返回 Enumeration 而在 HttpServletResponse 中返回 Collection?

java - 乘法时出现 NumberFormatException

java - 需要帮助在处理中将整数数组添加到数组列表

java - 文本未正确分割

html - Angular 2更改HTML元素的文本

angular - 在 Angular 上开发时无法自动完成和自动导入

typescript - Typescript 可以确保数组具有重复的类型模式吗?例如[字符串,数字,字符串,数字,....(永远)]

c++ - C++ 中的命名枚举