3

Is it possible to get the first item of an enum in typescript?

For example, Option.All in this enum:

enum Option {
    All = "all",
    Mine = "mine",
}

Tried, but won't compile:

const first: Option = Option[0]; // first should be All. This won't compile - Property '0' does not exist on type 'typeof Option'.
Julian
  • 33,915
  • 22
  • 119
  • 174
  • An enum becomes an object, which isn't an ordered data structure. There's only a 0th value if you let the compiler auto-number them from 0. But what's the context, why do you need the first value? – jonrsharpe Oct 15 '20 at 18:24
  • The enum code is generated and I need a default value. – Julian Oct 15 '20 at 18:25
  • What do you mean it's generated? If this isn't happening at compile time it's not really a TypeScript question, you're effectively asking https://stackoverflow.com/q/983267/3001761. – jonrsharpe Oct 15 '20 at 18:27
  • Well the generated code is Typescript, but out of my control. I can't change it, but need a (first) value. I could loop the enum, so there is an first in some sense. – Julian Oct 15 '20 at 18:29

2 Answers2

7

Option is essentially an Object.

This is how it is defined when compiled to JS:

var Option;
(function (Option) {
    Option["All"] = "all";
    Option["Mine"] = "mine";
})(Option || (Option = {}));

You can use Object.keys() or Object.values() to be able to convert an Object to an array.

Thus, in order to make first = 'All', you can use:

enum Option {
    All = "all",
    Mine = "mine",
}

const first = Object.keys(Option)[0];
console.log(first)

If you want to play around with how things look between TS and JS, you can use the TS Playground. I've loaded this link in with the code I showed here.


If you want the firstValue to be of type Option, use Object.values(Option)[0].

Typescript playground seems to have an issue with the name Option, so if you change it to Options, it shows correctly that first is of type Options: Playground

enum Options {
    All = "all",
    Mine = "mine",
}

const first = Object.values(Options)[0];
console.log(first) // 'all' of type Options

My local environment doesn't show that same weirdness.

Zachary Haber
  • 10,376
  • 1
  • 17
  • 31
2

Please try this:

Option[Object.keys(Option)[0]]
  • That gives: Element implicitly has an 'any' type because index expression is not of type 'number'.[Playground](https://typescript-play.js.org/#code/KYOwrgtgBAsgngeQA4BcCWB7EUDeAoKQqAQQBtSoBeKAIgENyaAaAomNEYK2iD4ZvAF88eAMZYAziigAzNACcpALliJUmbNXjJ0WANoIARgCtgolADoA1sDgSAFNvVYAlHoAMAXU9A) – Julian Oct 15 '20 at 18:27
  • @Julian You could write `Option[Object.keys(Option)[0] as keyof typeof Option]` – Johannes Riecken Dec 29 '22 at 09:13