Created
December 29, 2021 15:29
-
-
Save joshgrift/a251731e113dff071ea0ccd96f8f965e to your computer and use it in GitHub Desktop.
Iterate Over Typescript Enums
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
// 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]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
for (const tileColor of enumValues(TileColor))