Last active
May 6, 2024 20:23
-
-
Save andersonbosa/244233912b5d7949cfc425bf49ef7dad to your computer and use it in GitHub Desktop.
enum_typescript.ts
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
/* | |
In this article, we reviewed a few ways to iterate over the keys and values of enum types | |
in TypeScript. First, we used the inbuilt methods of any TypeScript object, noting that | |
they are fairly “low-level”. | |
Second, we moved to a higher-level approach, with for loops. We verified that we can teach | |
TypeScript to preserve the typing given by enums, without relying on the string or numeric | |
representation. | |
*/ | |
enum TrafficLight { | |
Green, | |
Yellow, | |
Red | |
} | |
Object.keys(TrafficLight).forEach((key, index) => { | |
console.log(`[TrafficLight:Object.keys] ${key} has index ${index}`) | |
}) | |
Object.values(TrafficLight).forEach((value, index) => { | |
console.log(`[TrafficLight:Object.values] ${Object.keys(TrafficLight)[index]} - ${value} has index ${index}`) | |
}) | |
for (const tl in TrafficLight) { | |
const value = TrafficLight[tl] | |
if (typeof value === "string") { | |
console.log(`[TrafficLight:for] Value: ${TrafficLight[tl]}`) | |
} | |
} | |
/* -------------------------------------- */ | |
enum StarRating { | |
TooBad, | |
Bad, | |
Neutral, | |
Good, | |
VeryGood | |
} | |
function enumKeys<O extends object, K extends keyof O = keyof O> (obj: O): K[] { | |
return Object.keys(obj).filter(k => !Number.isNaN(k)) as K[] | |
} | |
for (const tl of enumKeys(StarRating)) { | |
const value = StarRating[tl] | |
if (typeof value === "string") { | |
console.log(`[StarRating:enumKeys] Value: ${StarRating[tl]}`) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment