Array to enum in typescript with different solutions

 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:

  1. Manual Mapping:

    In this approach, you manually create an enum and map the array values to its members.

    typescript
    enum 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' }
  2. Enum with Union Type:

    Utilize a union type by combining the array values to create a dynamic enum.

    typescript
    const colorArray = ['Red', 'Green', 'Blue'] as const;
    type Color = typeof colorArray[number];

    console.log(Color.Red); // 'Red'
  3. Enum with Object Mapping:

    Create an enum by mapping array values to an object with enum-like properties.

    typescript
    const 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 মন্তব্যসমূহ