DEV Community

Joao Polo
Joao Polo

Posted on

TypeScript - Enum to Array

I'm working with some enums to ensure the typing for my models. But now, I needed to create a select box with that. I'll explain how to do that.

Considering a key/value enum, you can use the Object.entries to extract the data and create the array.

export enum EventModel {
  REPAIR = "Repair",
  PREVENT = "Prevent",
}

export const EventModelList: {
  key: string;
  value: string;
}[] = Object.entries(EventModel)
  .map(([key, value]) => ({ key, value }));
Enter fullscreen mode Exit fullscreen mode

So cool... but, if you have an enum without key=value association?

In this case, you need to get the values and filter only strings:

export enum OtherModel {
  MODEL_A,
  MODEL_B
}

export const OtherModelList: {
  value: string;
}[] = Object.values(OtherModel)
  .filter((value) => typeof value === "string")
  .map((value) => ({ value: value as string }));

Enter fullscreen mode Exit fullscreen mode

It was necessary because each value without an association generates two values: the key itself and the value (a number).

I created a simple sandbox to test that: codesandbox:ts-enum-as-array

Discussion (0)