In TypeScript, the keyof operator is used to obtain the keys (property names) of a type. When used with an object type, keyof returns the union of all the property names of that object type. However, when used with an enum, the keyof operator behaves differently.
An enum in TypeScript is a mapping between a set of named constants and their corresponding numeric values. By default, TypeScript assigns numeric values to the enum members starting from 0 and incrementing by 1 for each subsequent member. For example:
enum UserRole {
Admin, // 0
User, // 1
Guest, // 2
}
When you use keyof UserRole, TypeScript will return the union of the numeric keys ("0" | "1" | "2") instead of the actual enum member names ("Admin" | "User" | "Guest").
To get the actual enum member names as keys, you need to use keyof typeof UserRole. The typeof operator is used to obtain the type of the UserRole enum object, and then keyof is applied to this type to get the union of the actual enum member names ("Admin" | "User" | "Guest").
Here’s an example to illustrate this:
enum UserRole {
Admin,
User,
Guest,
}
type UserRoleKeys = keyof UserRole;
// Output: "0" | "1" | "2"
type UserRoleKeysWithtypeof = keyof typeof UserRole;
// Output: "Admin" | "User" | "Guest"
By using keyof typeof UserRole, you can work with the actual enum member names as keys, which is often what you want when dealing with enums in TypeScript.
Leave a Reply