2

I have an Enum in Java set up like so:

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

and I want to set up an equivalent Typescript Enum and I've done so like this:

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";
        }
    }
}

My question is, can I create a constructor function which has a description and sqlType in Typescript as well?

3
  • Did you read typescriptlang.org/docs/handbook/enums.html? Commented Jun 14, 2017 at 20:21
  • Yea thats where I got the idea for my initial enum configuration. but I am still confused as to how to add a sqlType and description field to this enum. In Java you can specify a constructor which contains additional fields. Can you mimic that behavior in Typescript enums? Commented Jun 14, 2017 at 20:26
  • From the link it is clear that you can not do that. enum in Typescript is just an alias for integers. Commented Jun 14, 2017 at 20:47

1 Answer 1

2

I'm not entirely sure if you can do that with typescript enums, but something along these lines should work:

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

From what I can tell, typescript enums basically translate to numbers, so this may be the only way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.