Question:
How can one convert an array to an enum in TypeScript? Provide various solutions for this task and explain each approach.
Answer: Converting an array to an enum in TypeScript involves mapping the array values to corresponding enum members. Below are several solutions to achieve this:
Manual Mapping:
In this approach, you manually create an enum and map the array values to its members.typescriptenum Color {
Red = 'Red',
Green = 'Green',
Blue = 'Blue',
}
const colorArray = ['Red', 'Green', 'Blue'];
const colorEnum: { [key: string]: Color } = {};
colorArray.forEach(color => {
colorEnum[color] = color as Color;
});
console.log(colorEnum); // { Red: 'Red', Green: 'Green', Blue: 'Blue' }Enum with Union Type:
Utilize a union type by combining the array values to create a dynamic enum.typescriptconst colorArray = ['Red', 'Green', 'Blue'] as const;
type Color = typeof colorArray[number];
console.log(Color.Red); // 'Red'Enum with Object Mapping:
Create an enum by mapping array values to an object with enum-like properties.typescriptconst colorArray = ['Red', 'Green', 'Blue'];
const ColorEnum = Object.freeze({
Red: colorArray[0],
Green: colorArray[1],
Blue: colorArray[2],
});
console.log(ColorEnum); // { Red: 'Red', Green: 'Green', Blue: 'Blue' }
These are just a few examples, and the choice of method depends on the specific use case and preferences. Each approach provides a way to convert an array to an enum in TypeScript, allowing for flexibility in implementation.
0 মন্তব্যসমূহ