Use an Enum as Restricted Key or Value type in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 26, 2024
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.

index.ts
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 };

use enum as restricted key or value type

The code for this article is available on GitHub

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.
index.ts
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.

index.ts
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' };
The code for this article is available on GitHub

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

index.ts
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.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev