Typescript array of objects with enum generic type

Typescript Array of Objects with Enum Generic Type

When working with TypeScript, you may come across a scenario where you need to create an array of objects with a generic type that includes an enum. This can be a bit tricky, but fear not! In this blog post, we will explore different solutions to this problem.

Solution 1: Using an Interface

One way to achieve this is by using an interface that defines the structure of the objects in the array. We can then use the enum as a property type within the interface.


enum Color {
  Red = "RED",
  Blue = "BLUE",
  Green = "GREEN"
}

interface MyObject {
  id: number;
  name: string;
  color: Color;
}

const myArray: MyObject[] = [
  { id: 1, name: "Object 1", color: Color.Red },
  { id: 2, name: "Object 2", color: Color.Blue },
  { id: 3, name: "Object 3", color: Color.Green }
];

In this solution, we define an enum called “Color” with three possible values. Then, we create an interface called “MyObject” that includes properties for “id” (number), “name” (string), and “color” (Color enum). Finally, we create an array called “myArray” that contains objects conforming to the “MyObject” interface.

Solution 2: Using a Type Alias

Another approach is to use a type alias instead of an interface. This allows us to define the structure of the objects in the array using the “type” keyword.


enum Color {
  Red = "RED",
  Blue = "BLUE",
  Green = "GREEN"
}

type MyObject = {
  id: number;
  name: string;
  color: Color;
};

const myArray: MyObject[] = [
  { id: 1, name: "Object 1", color: Color.Red },
  { id: 2, name: "Object 2", color: Color.Blue },
  { id: 3, name: "Object 3", color: Color.Green }
];

In this solution, we define the enum “Color” and then create a type alias called “MyObject” that represents the structure of the objects in the array. The rest of the code is similar to the previous solution.

Conclusion

When working with TypeScript and needing to create an array of objects with an enum generic type, you have multiple solutions at your disposal. You can use an interface or a type alias to define the structure of the objects in the array. Both approaches achieve the same result, so choose the one that best fits your coding style and project requirements.

Remember to always consider the specific needs of your project and choose the solution that provides the most clarity and maintainability for your codebase.


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *