Typescript enum key type

How to access the keys and values of an Enum (string and numeric) in TypeScript.

It is a special data type that can be used to define a set of named constants.

Important Note: The «enums» are real objects in TypeScript and they exist at the runtime. So we are able to use the «Object.keys()» and «Object.values()» methods on it.

Important Note: The «const enums» can only use constant enum expression and they are not available at runtime. So when following the examples, make sure you are not declaring as «const enum».

Let’s look at an example of an enum object.

enum Alphabets  Apple = "A", Bat = "B", Car = "C", Door = "D", >

String Enums

The example shown above is a string enum. They have strings as keys and values.

How to access all the keys of an enum?

We can use the «Object.keys()» method to get the keys of an enum.

enum Alphabets  Apple = "A", Bat = "B", Car = "C", Door = "D", > const keys = Object.keys(Alphabets); console.log(keys); // 👈 ["Apple","Bat","Car","Door"]

How to access all the values of an enum?

For accessing the values of an enum, we will use the «Object.values()» method.

enum Alphabets  Apple = "A", Bat = "B", Car = "C", Door = "D", > const values = Object.values(Alphabets); console.log(values); //👈 ["A","B","C","D"] 

How to access a specific value in an enum using the key.

For accessing a specific key value, you need to first find the index of the «key» that you are looking for. You can do that by combining the «Object.keys()» method and the «indexOf()» method. See the following code:

enum Alphabets < Apple = "A", Bat = "B", Car = "C", Door = "D", >const indexOfApple = Object.keys(Alphabets).indexOf("Apple"); console.log(indexOfApple); //👈 0 

We first retrieved the array of all the keys and then found the index of the key we are looking for. Now in order to get the key’s value, we need to retrieve the array of values using the «Object.values()» method and access the specified value using the index we just found.

enum Alphabets < Apple = "A", Bat = "B", Car = "C", Door = "D", >const indexOfApple = Object.keys(Alphabets).indexOf("Apple"); const valueofApple = Object.values(Alphabets)[indexOfApple]; console.log(valueofApple); //👈 "A"

Numeric Enum

Numeric enums are different from string enums since they store string values with a number key. We can either specify a number key or it will be implicitly given based on the index position in the object. Here is an example of a numeric enum:

enum NumericEnum  One, Two, Three, Four, >

Here is another example of a numeric enum with custom number keys assigned:

enum NumericEnum  One = 1, Three = 3, Five = 5, > 

How to access the values in a numeric enum?

We can directly access the value using either the index of the value or the numeric key we have assigned to the value. Let’s see examples for both scenarios.

enum NumericEnum < One, Two, Three, Four, >console.log(NumericEnum[0]); //👈 One console.log(NumericEnum[1]); //👈 Two console.log(NumericEnum[2]); //👈 Two console.log(NumericEnum[3]); //👈 Three

Now, let’s see a numeric enum with keys manually assigned to them.

enum NumericEnum < One = 1, Three = 3, Five = 5, >console.log(NumericEnum[1]); //👈 One console.log(NumericEnum[3]); //👈 Three console.log(NumericEnum[5]); //👈 Five

How to access all the keys or values of a numeric enum?

Simply using the «Object.values()» or «Object.keys()» method will return both the keys and values in a combined array.

enum NumericEnum < One, Two, Three, Four, >const values = Object.values(NumericEnum); console.log(values); //👈 ['One', 'Two', 'Three', 'Four', 0, 1, 2, 3] const keys = Object.keys(NumericEnum); console.log(keys); //👈 ['0', '1', '2', '3', 'One', 'Two', 'Three', 'Four'] 

In order to properly, get the values and keys of a numeric enum, we need to filter out the result accordingly.

We can filter the keys by only returning the numeric values since, in numeric enums, all the keys are numbers.

const keys = Object.keys(NumericEnum).filter((v) => isNaN(Number(v))); console.log(keys); //👈 [0, 1, 2, 3]

We can filter the values by only returning the non-numeric values.

const values = Object.values(NumericEnum).filter((v) => !isNaN(Number(v))); console.log(values); //👈 ['One', 'Two', 'Three', 'Four']

I hope my article was helpful to understand the methods used to access the values in different TypeScript enums. Check out my blog to see more articles.

Subscribe to Sharooq

Join the growing community of friendly readers through my monthly newsletter.

Источник

Typescript enum key type

Last updated: Jan 20, 2023
Reading time · 2 min

banner

# Use an Enum as Restricted Key or Value type in TypeScript

Use keyof typeof to use an enum as a restricted keys type.

The constructed type will contain all of the enum keys with their values being initialized to any .

Copied!
enum Sizes Small = 'S', Medium = 'M', Large = 'L', ExtraLarge = 'XL', > /** * 👇️ let values: S: any; M: any; L: any; XL: any> */ let values: [key in Sizes]: any >; /** * 👇️ let keys: Small: any; Medium: any; Large: any; ExtraLarge: any> */ let keys: [key in keyof typeof Sizes]: any >;

The first example shows how to construct a type that includes the enum values as keys and the second constructs a type using the enum keys.

If you don’t want to have all the keys or values in the constructed type be required, set them to optional by using a question mark.

Copied!
enum Sizes Small = 'S', Medium = 'M', Large = 'L', ExtraLarge = 'XL', > /** * 👇️ let values: S?: any; M?: any; L?: any; XL?: any> */ let values: [key in Sizes]?: any >; /** * 👇️ let keys: Small?: any; Medium?: any; Large?: any; ExtraLarge?: any> */ let keys: [key in keyof typeof Sizes]?: any >;

Now the consumer can only specify the keys they need.

Copied!
enum Sizes Small = 'S', Medium = 'M', Large = 'L', ExtraLarge = 'XL', > /** * 👇️ let values: S?: any; M?: any; L?: any; XL?: any> */ let values: [key in Sizes]?: any >; values = M: 'medium' >; /** * 👇️ let keys: Small?: any; Medium?: any; Large?: any; ExtraLarge?: any> */ let keys: [key in keyof typeof Sizes]?: any >; keys = Large: 'large' >;

When working with enums, keyof typeof constructs a type that represents all enum keys as strings.

Copied!
enum Sizes Small = 'S', Medium = 'M', Large = 'L', ExtraLarge = 'XL', > // 👇️ type KeysUnion = "Small" | "Medium" | "Large" | "Extra Large" type KeysUnion = keyof typeof Sizes;

If you need to check if a value exists in an enum, click on the following article.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

TypeScript keyof Enum

TypeScript keyof Enum

TypeScript keyof enum is the indexed type query operators. Enums in TypeScript have their own uses as such, common usage is the string enums used to represent a set of static values selectable by the user itself. Most probably, we use keyof operator to create a type whose elements are the member keys. TypeScript keyof will yield a union containing property names/ keys possible to its operand. Most of the time, keyof operator precedes object literals, the user-defined types. Keyof enum can be used against the primitive types which are not that useful. Keyof operator creates the type whose elements will be the keys of enum members. Let us see further how TypeScript keyof enum is used in coding and its syntax definition.

Web development, programming languages, Software testing & others

Here is the syntax of keyof enum in TypeScript. Before looking into the syntax of keyof enum, we need to know how keyof is used or its syntax,

keyof sample_key sample_key = Type;

So, here sample_key is the type for which keyof is being applied.

type keyofEnum = keyof sample_keys;

Here, sample_keys is an Enumerable type to which keyof is applied.

While using TypeScript keyof operator, we need to combine it with typeof operator, for example,

enum sample_keys < 'TypeScript', 'JavaScript', 'ExpressJS', 'NodeJS', 'NextJS' >type enum = keyof typeof sample_keys;

These TypeScript enums or enumerations allow users to declare a set of named constants. In simple language, Enum is a collection of related values of numeric or string data type.

Types of Enums in TypeScript

We have three types of enums in TypeScript:

Numeric Enums: These Numeric enums are number based enums. They store string type values as numbers. These are defined using keyword enum. For eg, Let us say a user wants to store a set of media types. TypeScript keyof enum can be written as follows,

enum socialMedia < Instagram, Facebook, Whatsapp, Snapchat >type enum = keyof typeof socialMedia;

In the above example, there is an enum socialMedia which has 4 values: Instagram, Facebook, Whatsapp, and Snapchat. As the enum key values start from 0 and get incremented by 1. It will look as follows,

Instagram = 0 Facebook = 1 Whatsapp = 2 Snapchat = 3

Enums are always assigned with numeric values on storing. Users also have an option to assign the first numeric value. The example above can also be designed as

As the first member is assigned with 1, the remaining members will have keyof incremented by 1. Hence, Facebook will have 2, Whatsapp will have 3, and Snapchat will have 4 as the keys.

Assigning sequentially to the enum members is not a necessity. TypeScript keyof enum members can have any key values assigned to them, as below.

This enum can be also used as a function parameter or as a return type, as below,

Example #1: TypeScript keyof Enum Basic example

enum socialMedia < Instagram = 1, Facebook, Whatsapp, Snapchat >type KeyofEnum = keyof socialMedia; function getsocialMedia(mediaOfficial: string): socialMedia < if (mediaOfficial === 'Filters' || mediaOfficial === 'Snaps') < return socialMedia.Snapchat; >> let mediaType: socialMedia = getsocialMedia('Snaps'); // returns Snapchat console.log('keyof enum string type Snapchat is', mediaType);

TypeScript keyof Enum 1

So here we are able to get the key of enum members.

Computed Enums: Enum members can also include keys with a computed numeric values. This value can either be a constant or computed. Let us check the below example for computed key values to enum members.

Example #2: TypeScript keyof Enum with Computed enum keys.

enum socialMedia < Instagram = 1, Facebook = getsocialMediaKey('Stories'), Whatsapp = Facebook *4, Snapchat = 6 >type KeyofEnum = keyof socialMedia; function getsocialMediaKey(mediaOfficial: string): number < if (mediaOfficial === 'Stories') < return 7; >> console.log('keyof enum string type Facebook is', socialMedia.Facebook); console.log('keyof enum string type Whatsapp is', socialMedia.Whatsapp); console.log('keyof enum string type Snapchat is', socialMedia.Snapchat);

TypeScript keyof Enum 2

Here we have computed keyof enums.

Note: Members which are already assigned with keys can only be used for computing values to the other enum members. Those members which are used before the assignment will compute to 0 even if the member is assigned a value later.

String Enums: These are similar to numeric enums but the enum values are initialized with string value instead of numeric values.

Using String enums gives better readability as it is easier to read the string values while debugging the code.

Example #3: TypeScript keyof enum string members

enum Employee < Delivery_Manager = "Karthik", Group_Project_Manager = "Saideep", Project_Lead = "Hari", TeamMate = "Siva" >// Accessing String Enum console.log('Accessing keyof enum Member', Employee.Project_Lead); console.log('Accessing keyof enum Member', Employee['Delivery_Manager']); console.log('Accessing keyof enum Member', Employee['Team_Mate']);

TypeScript keyof Enum 3

So here String enums have string keys. If there is no key defined or if there is no enum member, they keyof enum will be undefined.

Heterogeneous Enums: These enums contains both numeric and string values.

Conclusion

With this, we conclude our topic ‘TypeScript keyof enum’. We have seen the syntax and its description illustrated few examples above to know how to get the keyof enum member and display. We have discussed some important points to be noted which when implemented will give a better idea. Thanks! Happy Learning!!

We hope that this EDUCBA information on “TypeScript keyof Enum” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access

1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access

1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access

3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access

All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access

Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access

Источник

Читайте также:  Моя первая веб-страница
Оцените статью