Is there a simple way to get a list of keys/numbers from enum in typescript?

Issue

I would like a simple way to get a list of keys from an enumerator, I tried Object.keys, but it returned 6 keys, 0-5, I think it occours because when I tried foreach the enum, this returned keys and values list, is there a simple way to return only keys, I would not like to return to mount and return another list.

I will use this with react

My enum:

enum ObservationType {
    Accomodation = 1,
    Addtional = 2,
    LandTransport = 3
}

Sample that I tried and returned six values:

{Object.keys(ObservationType).map((type) => <div>{type}</div>)}

Solution

From the TypeScript enum documentation:

In this generated code, an enum is compiled into an object that stores both forward (name -> value) and reverse (value -> name) mappings. References to other enum members are always emitted as property accesses and never inlined.

Keep in mind that string enum members do not get a reverse mapping generated at all.

This means that if you’re able, you may want to use string enums, e.g.:

enum ObservationType {
  Accomodation = 'Acc',
  Addtional = 'Addt',
  LandTransport = 'LandT',
}

// Object.keys will only have the three keys.

Another way to handle this would be to keep track of the mapped values to get the reverse mappings only once. This requires the numeric keys of the object to be set first which is not necessarily a guarantee:

enum ObservationTypeNums {
  Accomodation,
  Addtional,
  LandTransport,
}

Object.keys(ObservationTypeNums).reduce((arr, key) => {
  if (!arr.includes(key)) {
    arr.push(ObservationTypeNums[key]);
  }
  return arr;
}, []);

// arr now has only the string keys

Otherwise you will just have to filter out numeric keys in a way as you have done.

Answered By – Explosion Pills

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published