Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first enum item from an enum

Tags:

typescript

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'.
like image 495
Julian Avatar asked Sep 03 '26 21:09

Julian


1 Answers

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.

like image 169
Zachary Haber Avatar answered Sep 06 '26 10:09

Zachary Haber