Skip to content

Instantly share code, notes, and snippets.

@joshgrift
Created December 29, 2021 15:29
Show Gist options
  • Save joshgrift/a251731e113dff071ea0ccd96f8f965e to your computer and use it in GitHub Desktop.
Save joshgrift/a251731e113dff071ea0ccd96f8f965e to your computer and use it in GitHub Desktop.
Iterate Over Typescript Enums
// Credit due: https://github.com/microsoft/TypeScript/issues/4753#issuecomment-694557208
function enumValues<T extends string>(enumObj: {
[key: string]: T;
}): IterableIterator<T>;
function enumValues<T extends string | number>(enumObj: {
[key: string]: T;
}): IterableIterator<Exclude<T, string>>;
function* enumValues<T>(enumObj: { [key: string]: T }): IterableIterator<T> {
let isStringEnum = true;
for (const property in enumObj) {
if (typeof enumObj[property] === "number") {
isStringEnum = false;
break;
}
}
for (const property in enumObj) {
if (isStringEnum || typeof enumObj[property] === "number") {
yield enumObj[property];
}
}
}
@joshgrift
Copy link
Author

Usage: for (const tileColor of enumValues(TileColor))

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