Skip to content

Instantly share code, notes, and snippets.

@jickoo
Created July 25, 2023 09:06
Show Gist options
  • Save jickoo/ae35581b45cea6c961305c6b61ee337a to your computer and use it in GitHub Desktop.
Save jickoo/ae35581b45cea6c961305c6b61ee337a to your computer and use it in GitHub Desktop.
Typescript enum
// 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