Last updated: Feb 26, 2024
Reading timeยท2 min
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
.
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.
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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: