Last active
July 16, 2019 03:33
-
-
Save MichaelXavier/7714513 to your computer and use it in GitHub Desktop.
to/from enum converter in TypeScript using generics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"))); |
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
+1 for exception message.