Is below a valid use of an enum in an interface?
declare enum MyEnumType {
Member1,
Member2,
}
interface Foo {
prop1: MyEnumType, // this is valid
prop2: MyEnumType.Member1 // how about this? If not, why?
}
If you run this code in a sandbox, you will get an Error:
Enum type 'MyEnumType' has members with initializers that are not literals.
It is invalid only if you declare the enum. In this case you tell TS that enum exists, but you don't tell it what are it's values, because the definition of this enum could be like this:
enum MyEnumType {
Member1 = 8,
Member2 = 'RaNdOmWhAtEvEr'
}
This means MyEnumType.Member2 is ambiguous. It will works if you
declare keyword). Now TypeScript is in full control of the enum and it knows it will assign values 0 and 1 to its keysdeclare enum MyEnumType {
Member1 = 0,
Member2 = 1
}
Now TS knows what to expect from the enum and is able to operate with its keys as types.