hansi
hansi

Reputation: 2308

Typescript from cryptic value to readable enum

I retrieve data from a service where enums would come in handy. The data comes in somewhat inconvenient for readability but I would like the enum to be more readable.

How can I instantiate the enum value from inconvenient string?

export enum Status {
     ENROLLED = "a",
     PENDING = "asdf", 
     NOT_ENROLLED = "f"
}

let incoming = "asdf";
let status: Status = ...?

Upvotes: 0

Views: 60

Answers (1)

jcalz
jcalz

Reputation: 329523

Well, if you don't care about safety (checking incoming for validity), you can just assert that incoming is of type Status:

let status: Status = incoming as Status; 

That's because Status is a subtype of string (actually a subtype of the string literal values "a"|"asdf"|"f").


If you do care about safety, you can make a function to check first and return undefined or throw an exception if the string isn't a valid Status:

function toStatus(x: string): Status | undefined {
  return (Object.keys(Status).some(k => Status[k as any] === x)) ? x as Status : void 0;
}

let status: Status | undefined = toStatus(incoming);

if (!status) {
  // invalid status
  console.log("I am sad.");
} else {
  // valid status
  console.log("I am happy.");
  switch (status) {
    // ... whatever you want to do here
  }
}

Hope that helps; good luck!

Upvotes: 1

Related Questions