We can use members as if they were literals such as true, or 'abc' — for example:. Each enum member has a name and a value. The default for enums is to be numeric.
That is, each member value is a number:. We can omit the value of a member if the preceding member value is a number. Then TypeScript increments that value by one and uses it for the current member:. There is no way to compute the names of enum members. Object literals support computed names via square brackets.
The last kind of enums is called heterogeneous. The member values of a heterogeneous enum are a mix of numbers and strings:. Note that the previously mentioned rule applies here, too: We can only omit an initializer if the previous member value is a number. Alas, TypeScript only supports numbers and strings as enum member values. Other values, such as symbols, are not allowed. Constant enum members are initialized via expressions whose results can be computed at compile time.
In this list, earlier entries are less flexible, but support more features. The next subsections cover each entry in more detail. If an enum has only literal members, we can use those members as types similar to how, e. An enum member is constant if its value can be computed at compile time. Therefore, we can either specify its value implicitly that is, we let TypeScript specify it for us.
Or we can specify it explicitly and are only allowed to use the following syntax:. But we can still do exhaustiveness checks. The values of computed enum members can be specified via arbitrary expressions. For example:. This was a numeric enum.
String-based enums and heterogeneous enums are more limited. For example, we cannot use method invocations to specify member values:.
When using the enum as a type, the values that are allowed statically are not just those of the enum members — any number is accepted:. Daniel Rosenwasser explains :. The behavior is motivated by bitwise operations. There are times when SomeFlag. Foo SomeFlag. Bar is intended to produce another SomeFlag. In the Node. Its value is used to specify file permissions, via an encoding that is a holdover from Unix:.
Bit patterns are combined via bitwise Or :. The main idea behind bit patterns is that there is a set of flags and that any subset of those flags can be chosen.Enums allow us to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums. An enum can be defined using the enum keyword. Above, we have a numeric enum where Up is initialized with 1. All of the following members are auto-incremented from that point on.
In other words, Direction. Up has the value 1Down has 2Left has 3and Right has 4. Here, Up would have the value 0Down would have 1etc. This auto-incrementing behavior is useful for cases where we might not care about the member values themselves, but do care that each value is distinct from other values in the same enum. Using an enum is simple: just access any member as a property off of the enum itself, and declare types using the name of the enum:.
Numeric enums can be mixed in computed and constant members see below. The short story is, enums without initializers either need to be first, or have to come after numeric enums initialized with numeric constants or other constant enum members. String enums are a similar concept, but have some subtle runtime differences as documented below. In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member.
Each enum member has a value associated with it which can be either constant or computed. An enum member is considered constant if:. It does not have an initializer and the preceding enum member was a numeric constant. In this case the value of the current enum member will be the value of the preceding enum member plus one. The enum member is initialized with a constant enum expression.
A constant enum expression is a subset of TypeScript expressions that can be fully evaluated at compile time. An expression is a constant enum expression if it is:. It is a compile time error for constant enum expressions to be evaluated to NaN or Infinity. A literal enum member is a constant enum member with no initialized value, or with values that are initialized to.
The first is that enum members also become types as well! For example, we can say that certain members can only have the value of an enum member:. The other change is that enum types themselves effectively become a union of each enum member. Because of that, TypeScript can catch silly bugs where we might be comparing values incorrectly.
For example:. In that example, we first checked whether x was not E. Even though Enums are real objects that exist at runtime, the keyof keyword works differently than you might expect for typical objects. Instead, use keyof typeof to get a Type that represents all Enum keys as strings. In addition to creating an object with property names for members, numeric enums members also get a reverse mapping from enum values to enum names.Enums or enumerations are a new data type supported in TypeScript.
Most object-oriented languages like Java and C use enums. This is now available in TypeScript too. In simple words, enums allow us to declare a set of named constants i.
Enums can be defined using the keyword enum. Let's say we want to store a set of print media types. The corresponding enum in TypeScript would be:.
In the above example, we have an enum named PrintMedia. The enum has four values: Newspaper, Newsletter, Magazine, and Book. Here, enum values start from zero and increment by 1 for each member. It would be represented as:.
Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1. We also have the option to initialize the first numeric value ourselves. For example, we can write the same enum as:.
The first member, Newspaper, is initialized with the numeric value 1. The remaining members will be incremented by 1 from the numeric value of the first value.
Thus, in the above example, Newsletter would be 2, Magazine would be 3 and Book would be 4. In the above example, we declared an enum PrintMedia. Next, we declare a function getMedia that takes in an input parameter mediaName of the type string.
This function returns an enum PrintMedia. In the function, we check for the type of media. If the media name matches 'Forbes' or 'Outlook', we return enum member PrintMedia. Numeric enums can include members with computed numeric value. The value of an enum member can be either a constant or computed.
The following enum includes members with computed values. When the enum includes computed and constant members, then uninitiated enum members either must come first or must come after other initialized members with numeric constants.
Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. What would be the best way in TypeScript 0. TypeScript 2. So it's possible to end up with an enum that look like the following:. I think the best way to do this is to create your own functions ex.
Subscribe to RSS
Using enums in this way does not preserve this goal. I used the solution proposed by David Sherret and wrote an npm library you can use named enum-values If you want to associate strings values to your enum these methods don't works. To have a generic function you can do :. Learn more. How to programmatically enumerate an enum type? Ask Question. Asked 6 years, 2 months ago.
The best way I found is by getting all Enum Values as an array and using indexOf on it. But the resulting code isn't very legible:. If you want this to work with string enums, you need to use Object. If you get an error for: Property 'values' does not exist on type 'ObjectConstructor'then you are not targeting ES You can either use this tsconfig. If you are using TypeScript, you can use an actual enum.
Then you can check it using in. Learn more. Check if value exists in enum in TypeScript Ask Question. Asked 2 years, 11 months ago. Active 1 month ago. Viewed 86k times. Tim Schoch Tim Schoch 1, 2 2 gold badges 9 9 silver badges 20 20 bronze badges. There's not much you can do.
TimSchoch You can just do!! Kevin Babcock That will fail of one of the enum values maps to 0though. Active Oldest Votes. Xiv Xiv 3, 2 2 gold badges 20 20 silver badges 29 29 bronze badges. This should be the accepted answer. K Mar 21 '18 at This does not work in typescript. JerinJoseph which versions of IE didn't work, and what solution did work for you? Saravana Saravana Only with proper enums. I'll check why we're not using a proper enum and see if we can change it. This does not work with string enums because they are not reverse mapped: typescriptlang.
The trouble with TypeScript enums
Ester Kaufman Ester Kaufman 7 7 silver badges 14 14 bronze badges. Thank you Ester for your answer. TimSchoch I can confirm this works very well at least for numeric enums. This is the most elegant solution imho.
Apr 4 '19 at TimSchoch Yes! It works for strings too. Note that this does NOT work for string enums if the enum uses string initializers with different values than the enum member names.In TypeScript, enums have a few surprising limitations. In particular, it can be challenging to check whether or not a value is in an enum in a type-safe way. A common use for string enums is to represent a set of static values, such as a set of options selectable by the user.
For example, if we wanted to model a list of fruits to use in a select element, we might model those values as a Fruits enum. An enum easily translates into an array of strings because we can call Object. But what about when we want to convert a string the user selected into our enum type? I have often seen something like the following example used to accomplish that.
In the following TypeScript Playground example, the --strict flag and therefore inherently the --noImplicitAny flag is enabled, meaning this code will not compile:. After all, if you were to console. Fruits[value] and get back a type of Fruits undefined? This opens us up to a runtime error where our constant fruit may in fact be undefined.
Disabling --noImplicitAny just further hides these types of casts, as well as the issues they introduce into a codebase. But as I discovered, the solutions are less than ideal. It turns out that even without the explicit predicate function, TypeScript can infer the same type if we use the Array. Since TypeScript 3. We can define our set of values as an array, and apply a const assertion :.
Enums can be challenging to use if you frequently need to check for existence of a string or numeric value within them. If — like in our above example — you need both the type and the associated values, we saw a way to access them in a type-safe way.
Alternately, since TypeScript 3. A practical example A common use for string enums is to represent a set of static values, such as a set of options selectable by the user. Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Fruits'. No index signature with a parameter of type 'string' was found on type 'typeof Fruits'.
Sometimes you don't need to try to workaround a problem with a specific approach you have, you can maybe just change the approach. In this case, you can use your own object:. Learn more. Is there any way to check if an object is a type of enum in TypeScript? Ask Question. Asked 3 years, 2 months ago. Active 2 years, 11 months ago. Viewed 5k times. Why do you want to check if it's an enum?
What do you mean by "check"--check at run-time? But enums are a compile-time construct. Check before compile time. As to why: I want to convert the object to an array and want to know whether I need to remove half the object's properties.
I was wondering if there was a very clean way to know if the object is of this type of data structure before attempting the conversion.
Active Oldest Votes. Edit Sometimes you don't need to try to workaround a problem with a specific approach you have, you can maybe just change the approach. Nitzan Tomer Nitzan Tomer But is there a way to detect before compile time? Is there a way that typescript might detect such a thing?