Last active
January 13, 2017 05:56
-
-
Save akdor1154/3f968e7f7d5836fd76fe52f1d659d6a0 to your computer and use it in GitHub Desktop.
Make Typescript enums display as their string value
This file contains 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 Categorization { | |
Sunny, | |
Clear, | |
MostlySunny, | |
Cloudy, | |
Hazy, | |
LightRain, | |
Windy, | |
Fog, | |
Shower, | |
Rain, | |
Dusty, | |
Frost, | |
Snow, | |
Storm, | |
LightShower, | |
HeavyShower, | |
Cyclone | |
}; | |
const weather1 = Categorization.Sunny; | |
console.log(weather1) // outputs "0". :( | |
fixEnum(Categorization); | |
const weather2 = Categorization.Sunny; | |
console.log(weather2) // outputs "Sunny". :) |
This file contains 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
function fixEnum(myEnum: any): void { | |
class EnumMember extends Number { | |
toString(): string { | |
return myEnum[this.valueOf()] | |
} | |
inspect(): string { | |
return this.toString(); | |
} | |
} | |
for (let key in myEnum) { | |
if ((typeof key !== 'string') || (parseInt(key).toString() === key)) { | |
console.log(`not touching ${key}`) | |
continue; | |
} | |
const oldVal = myEnum[key]; | |
if (typeof oldVal !== 'number') { | |
throw new Error(`unexpected! enum[${key}: ${typeof key}] == ${oldVal}: ${typeof oldVal}`); | |
} | |
myEnum[key] = new EnumMember(oldVal); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment