Created
March 21, 2023 09:52
-
-
Save VehpuS/27bdc52d2ac1ba362c53b911b9521d0d to your computer and use it in GitHub Desktop.
Programmatically get enum keys / values in TypeScript
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
// Playground URL: https://www.typescriptlang.org/play?#code/KYOwrgtgBAKsDOAXKBvAUFTUCGUC8UARAIKEA0GWARvkQELmWYDGtAjBQL5prMD2IeHwA2wAHTC+AcwAUhAKLhoAa2ABPeOSgB5KgCtgzRGNUaZcJAEoxAMwCWwxMABOMmQDdL+AHxQ78ADlsAJkAyCoXD0toyx4bMBAjOwEoUEgANWxhMAQAGX9EAB4YVIAPJxAAE3hUTm8ZNIgYPgBhAXcXRAAuWEsemABtUz4bWABdAbHUJih+QWRTGoJdAyMTdXgGpWa2kA7nRGt7R0ionz9A4NDwyM9ogG4Z52BEMGcQKEWxCGwABxllOdGjt2p0hjgasNRjAxpZHtxeAIkFAnEhMtkEP0EIhJrRGuicvB8khzNi4Tw5kJRBJpHJFJAoO4soStKjEASEOSgA | |
enum Test { | |
a = "A", | |
b = "B", | |
c = 1, | |
} | |
console.log("Enum keys", Object.keys(Test).filter((v) => isNaN(Number(v)))) | |
function enumValuesList<T extends {}>(enumToConvert: T): T[keyof T][] { | |
const keys = Object.keys(enumToConvert).filter((v) => isNaN(Number(v))); | |
return keys.map(k => enumToConvert[k as keyof T]); | |
} | |
const testValues: Test[] = enumValuesList(Test); | |
console.log("Enum values", testValues); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment