Skip to content

Instantly share code, notes, and snippets.

@akdor1154
Last active January 13, 2017 05:56
Show Gist options
  • Save akdor1154/3f968e7f7d5836fd76fe52f1d659d6a0 to your computer and use it in GitHub Desktop.
Save akdor1154/3f968e7f7d5836fd76fe52f1d659d6a0 to your computer and use it in GitHub Desktop.
Make Typescript enums display as their string value
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". :)
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