Use keyof typeof for enums#5
Conversation
|
Hi qix, Could you explain more about your case? From my understanding, I think you mean that TypeScript treats However, in my projects I have to use the enum values to assign to a variable with corresponding enum type. E.g: enum Color {
RED = 'RED',
GREEN = 'GREEN',
BLUE = 'BLUE'
}
const color1: Color = Color.RED; // this one is ok
const color2: Color = 'RED'; // TypeScript complains in this casehowever, compare enum value with string is ok switch (color1) {
case 'RED': // fine
case Color.R: // fine
case 'YELLOW': { // TypeScript complains in this case
break;
}
default: {
break;
}
}I'm not sure whether if it's due to some different in The reason why I need to clarify this is because there is a catch here: // note that the enum keys were changed to R/G/B instead of RED/GREEN/BLUE
enum Color {
R = 'RED',
G = 'GREEN',
B = 'BLUE'
}
const color1: Color = Color.R;
console.log(color1); // RED
const color2: keyof typeof Color = 'R'; // assign 'RED' will make TypeScript complains
console.log(color2); // RThis catch is not a problem in this library since the enum keys and values are always the same. However, it could lead to some troubles in the future :) Maybe we could wrap your implementation in a config option? |
Enum types in TypeScript are not actually just the enum values. The types land up being restricted to
stringinternally rather than the actual values. This makes the types a little stricter.