Created
July 25, 2023 09:06
-
-
Save jickoo/ae35581b45cea6c961305c6b61ee337a to your computer and use it in GitHub Desktop.
Typescript enum
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
// String | |
enum Family { | |
Mom = 'M', | |
Daddy = 'D', | |
Brother = 'B', | |
} | |
const indexOf = Object.values(Sizes).indexOf('M' as unknown as Family); | |
const key = Object.keys(Family)[indexOf]; | |
console.log(key); // "Mom" | |
// Numeric | |
enum FamilyNum { | |
Mom, | |
Daddy, | |
Brother, | |
} | |
console.log(SizesNumeric[0]); // "Mom" | |
console.log(SizesNumeric[1]); // "Daddy" | |
enum Family { | |
Mom = 'M', | |
Daddy = 'D', | |
Brother = 'B', | |
} | |
console.log(Object.keys(Sizes)); | |
// ['Mom', 'Daddy', 'Brother'] | |
console.log(Object.values(Sizes)); | |
// ['M', 'D', 'S'] | |
enum Family { | |
Mom = 'M', | |
Daddy = 'D', | |
Brother = 'B', | |
} | |
function getKeyByValue(value: string) { | |
const index = Object.values(Family).indexOf(value as unknown as Family); | |
const key = Object.keys(Family)[index]; | |
return key; | |
} | |
console.log(getKeyByValue('M')); // Mom | |
console.log(getKeyByValue('D')); // Daddy |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment