let c: Circle = { kind: ShapeKind.Square, // Error, cuz ShapeKind.Square is not assignable to type ShapeKind.Circle radius: 100 };
Feature Two: the enum types become a union of each enum member, with which the type system can know the exact set of values that exist in the enum, and can catch some simple bugs.
1 2 3 4 5 6 7 8 9
enum E { Foo, Bar }
functionfunc(e: E) { // Error: This condition will always return 'true' since the types 'E.Foo' and 'E.Bar' have no overlap. if(e !== E.Foo || e !== E.Bar) { ... } }
Enums at runtime
Enums are real objects that exist at runtime.
1 2 3 4 5 6 7 8 9 10 11
enum E { X, Y, Z }
functiongetX(obj: { X: number }) { return obj.X; }
getX(E); // OK, cuz E has a property named X which is a number
Enums at compile time
I’m a little bit confused about this…maybe just write it down first. Even though Enums are real objects that exist at runtime, the keyof keyword works differently than you might expect for typical objects. Instead, use keyof typeof to get a Type that represents all Enum keys as strings.