Skip to content

Instantly share code, notes, and snippets.

@MichaelXavier
Last active July 16, 2019 03:33
Show Gist options
  • Select an option

  • Save MichaelXavier/7714513 to your computer and use it in GitHub Desktop.

Select an option

Save MichaelXavier/7714513 to your computer and use it in GitHub Desktop.
to/from enum converter in TypeScript using generics
enum Status {
Pending,
PaymentReceived,
Shipped
}
class EnumConverter<E> {
toEnum(orig : string) : E {
return this.enumMap()[orig];
}
fromEnum(enumVal : E) : string {
var map = this.enumMap(),
val;
for(var k in map) {
val = map[k];
if (val == enumVal) return k;
}
throw("SHIT");
}
enumMap() : {[k: string] : E} {
throw "Abstract, ya dingus!"
}
}
class StatusConverter extends EnumConverter<Status> {
enumMap() {
return {
"Pending": Status.Pending,
"Payment Received": Status.PaymentReceived,
"Shipped": Status.Pending
};
}
}
var converter = new StatusConverter();
console.log(converter.fromEnum(converter.toEnum("Payment Received")));
@ParaSwarm

Copy link
Copy Markdown

+1 for exception message.

@ParaSwarm

Copy link
Copy Markdown

Also, enumMap's "shipped" is mapped to Status.Pending, rather than Status.Shipped. Just sayin'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment