As a result, the generated code will have a smaller size. This means that numbers can be assigned to an instance of the enum, and so can anything else that is compatible with number. In typescript enum is available from typescript version 2.4. In typescript we can have string enums as well. in the enum rather than magic values like 1, 2, 3,… This makes the code more obvious. We can validate that the Level enum represents a zero-based auto-incrementing number by outputting the values to the console: What if we assign the enum variable to a number that is isn’t 0, 1 or 2: No type error occurs! Enum is a collection of value the can be of type string or numeric as a named constants. Enums are a type that can make code more readable, where the meaning of the value of a variable is not apparent. Otherwise, it should throw a type error. For string-valued enum members, this mapping object defines mappings from key to value, but not vice versa: This means we can resolve a value by its key, but we cannot resolve a key by its value: Compare this to an enum with number-valued members: In this case, the compiler additionally emits a reverse mapping from value to key: This reverse mapping allows use to resolve both a key by its value and a value by its key: To avoid paying the cost of the generated enum mapping code, we can turn our MediaTypes enum into a const enum by adding the const modifier to the declaration: With the const modifier in place, the compiler will not emit any mapping code for our MediaTypes enum. String enums. For example, consider a selection of shirt sizes. Enum in TypeScript allows us to define a set of named constants. An enum is short for enumeration and is a type that represents named constants. How TypeScript enum works. In the below example, Chars Enum is declared with constants but not its value, Numbers are assigned (A=0, B=1, C=2, D=3) Here the number is compared against Enum numeric values. 0. For example in Java you can write: enum Colors {RED("Red"), GREEN("Green"), BLUE("Blue")} and you can get the enum key by the value and reverse. Defining a type for object properties that are strings. Since TypeScript 2.4 it's possible to declare string enums: enum MimeType { JPEG = 'image/jpeg', PNG = 'image/png', PDF = 'application/pdf', } You can explicitly provide numeric values using the same method. If you think about inputs such as dropdowns or radio buttons where the user must select a single value from multiple choices, the underlying values oftentimes map nicely to an enum data structure. Starting from TypeScript 2.4, the enum would not contain the key as a member anymore. A handy feature of enums is that you can also go from a numeric value to the name of that value in the enum. You’ll see why later When we run this code, we see: So that’s a special thing to note! enum Colors { Red = "RED", Green = "GREEN", Blue = "BLUE" } The caveat is that string-initialized enums can’t be reverse-mapped to get the original enum member name. (To me, enums have always felt like they go against the TS design goals since they're an expression-level syntax with non-trivial emit behavior and nominal by default.) It is now possible to assign a string value to an enum member: write regular, modern-day JavaScript. The caveat is that string-initialized enums can't be reverse-mapped to get the original enum member name. However, the following example passes a number instead of an enum to the isItSummer() function. TypeScript has a discrete enum type that allows various compile-time checks and constraints to be enforced when using such types. It is arguably easier to understand than the first if statement. 3. TypeScript provides both … Sometimes, it might be necessary to emit the mapping code for a const enum, for instance when some piece of JavaScript code needs access to it. TypeScript emits some mapping code for each enum which constructs a mapping object. Most object-oriented languages like Java and C# use enums. String enums do not have auto-incrementing behavior. a collection of related values that can be numeric or string values. In other words, you can't write Colors["RED"] to get the string "Red". Let’s create an enum in TypeScript to represent the days of the week: 1 2 3 4 5 6 7 8 9 Enum or Enumeration allowed us to declare set of named constants. 2.If the string is part of the enum name entry the value will be returned. One of Javascript’s most glaring omissions is first-class support for enums. Differences between generic and explicit types This separates the enum options from strings or integers, for example. It is now possible to assign a string value to an enum member: The string enum can be used like any other enum in TypeScript: Here's the ES3/ES5 output that the compiler generates for the above code: This output almost looks like the output that the compiler would generate for enums with numeric members, except that there's no reverse mapping for string-valued members. So, when declaring your types, you'll need to export the string literal type and use it the same way you would use an enum. TypeScript 2.4 implemented one of the most requested features: string enums, or, to be more precise, enums with string-valued members. TypeScript does not generate code for the union of string literals. I have always used the string-based enum, which I will use for all the examples in this post: My solution: Enum values can be string’s if we explicitly define a string value after the name. TypeScript 2.4 implemented one of the most requested features: string enums, or, to be more precise, enums with string-valued members. 1.Pass the given string to Enum object as a key. If you to learn more about TypeScript, you may find my free TypeScript course useful: Subscribe to receive notifications on new blog posts and courses. The above array contains enum values as string type. The second if statement uses an enum. 0. TypeScript provides the enum keyword to define a set of labeled values. There are many ways we can iterate enum … This will also prevent you from assigning a traditional "string" type to the string literal. You might find some of my other posts interesting: // type error - type '"VH"' is not assignable to type 'Level', Controlling Type Checking Strictness in TypeScript, Inferring Object and Function Types in TypeScript, Type-safe Data Fetching with unknown in TypeScript. Compare Number in enum type in Typescript. Use string enum value in TypeScript interface as a computed property key. Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Specifying enum member values # TypeScript distinguishes three ways of specifying enum member values: Literal enum members are initialized: implicitly or; via number literals or string literals (explicitly). This would get closer to a world where enums aren't necessary at all. TypeScript 2.4 now allows enum members to contain string initializers. Enum is called Enumeration, It is a new syntax for replacing define multiple constants declaration, Enum type contains constants of Strings and numbers only. In a string enum, each enum values are constant-initialized with a string literal, or with another string enum member rather than numeric values. Take this enum: Now add this code to log the values: Note: I’m using a separate log function to show what type the value is. If the strings are meaningful and don’t need to be mapped to something more meaningful, then a string literal union is a concise way of creating the type. String enums are useful when the meaning of string value isn’t apparent because it can be given a meaningful name to help the readability of the code. I had previously used them in C# and felt a reassuring familiarity. enum Day { BeforeNoon = "AM", AfterNoon = "PM" } In this case we can directly get names of enum by looping string enum object. This will not work if --noImplicitAny is enabled and throws an error // To Enum / number var month : Month = Month ["JAN"]; Other approach when - … The const type declaration syntax would also let you create a structurally-typed string enum like this: Enums or enumerations are a new data type supported in TypeScript. In other words, you can’t write Colors ["RED"] to … If the strings are meaningful and don’t need to be mapped to something more meaningful, then a string literal union is a concise way of creating the type. 3.And then cast it to the enum object to get enum type of string. That’s perhaps not what we expected. Instead, it will inline the value for each enum member at all use sites, potentially saving a few bytes and the overhead of the property access indirection: But what if, for some reason, we need access to the mapping object at runtime? However, it is recommended not to create an enum … Non-enum values can be mistaken for enum values statically or at runtime (if we use string-valued properties).