Manually mapping Enum to Object
Consequently, treating enum members as object keys has a one-to-one relationship with their corresponding values.
Syntax:
// Enum
enum Name {
Value1 = 'VALUE1',
Value2 = 'VALUE2',
}
// Object
const obj: Record<Name, ValueType> = {
[Name.Value1]: 'correspondingValue1',
[Name.Value2]: 'correspondingValue2',
};
Example: The below code maps a enum to a JavaScript object.
enum F {
S = 'STRAWBERRY',
M = 'MINT',
B = 'BLUEBERRY',
}
const FC: Record<F, string> = {
[F.S]: 'FF0000',
[F.M]: '00FF00',
[F.B]: '0000FF',
};
console.log("Flavor Codes:", FC);
Output:
Flavor Codes: {
STRAWBERRY: 'FF0000',
MINT: '00FF00',
BLUEBERRY: '0000FF'
}
How to map Enum/Tuple to Object in TypeScript ?
Mapping enum or tuple values to objects is a usual action in TypeScript when working with different data representations. Enumerations (enum) and Tuples are two types of data that can be mapped into objects differently based on the methods below in TypeScript.
Table of Content
- Manually mapping Enum to Object
- Manually mapping tuple to object
- Using Object.fromEntries() with Enum
- Mapping Tuple to Object with Reduce
Contact Us