Use an Enum as Restricted Key or Value type in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 14, 2022

banner

Photo from Unsplash

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

Use keyof typeof to use an enum as a restricted keys type, e.g. let keys: { [key in keyof typeof Sizes]: any }. 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 };

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' };

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