EDUCBA

EDUCBA

MENUMENU
  • Blog
  • Free Courses
  • All Courses
  • All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript keyof Enum

TypeScript keyof Enum

Asapu Harika
Article byAsapu Harika
Priya Pedamkar
Reviewed byPriya Pedamkar

Updated April 11, 2023

TypeScript keyof Enum

Introduction to 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.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

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 Enum
  • String Enum
  • Heterogeneous Enum

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

enum socialMedia {
Instagram = 1,
Facebook,
Whatsapp,
Snapchat
}

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.

enum socialMedia {
Instagram = 1,
Facebook = 10,
Whatsapp = 15,
Snapchat = 20
}

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

Example #1: TypeScript keyof Enum Basic example

Code:

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);

Output:

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.

Code:

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);

Output:

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

Code:

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']);

Output:

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.

For example,

enum Employee {
Boolean = "True",
Pending = 1,
Closed = 0
}

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!!

Recommended Articles

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

  1. TypeScript Abstract Class
  2. TypeScript Question Mark
  3. TypeScript Decorators
  4. Typescript for loop
All in One Excel VBA Bundle
500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access
Financial Analyst Masters Training Program
2000+ Hours of HD Videos
43 Learning Paths
550+ Courses
Verifiable Certificate of Completion
Lifetime Access
All in One Data Science Bundle
2000+ Hour of HD Videos
80 Learning Paths
400+ Courses
Verifiable Certificate of Completion
Lifetime Access
All in One Software Development Bundle
5000+ Hours of HD Videos
149 Learning Paths
1050+ Courses
Verifiable Certificate of Completion
Lifetime Access
Primary Sidebar
All in One Software Development Bundle5000+ Hours of HD Videos | 149 Learning Paths | 1050+ Courses | Verifiable Certificate of Completion | Lifetime Access
Financial Analyst Masters Training Program2000+ Hours of HD Videos | 43 Learning Paths | 550+ Courses | Verifiable Certificate of Completion | Lifetime Access
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more