Runtime does not recognize Typescript types as they do not generate any runtime artifacts due to type erasure.
In contrast, Enums in Typescript are a standalone feature that is not merely a type-level extension of JavaScript.
Typescript types serve to describe and restrict the code statically, rather than vice versa. Creating a Type based on an Enum for type safety is logical, but the reverse does not hold true.
Consider this thought experiment: Can you envision a scenario where defining an Enum from a type is more appropriate than the opposite?
Keep in mind that an Enum implicitly defines its own type. As shown in the Typescript documentation on Enums:
enum UserResponse {
No = 0,
Yes = 1,
}
function respond(recipient: string, message: UserResponse): void {
// ...
}
If the enum members are declared as const values, it results in a union enum, functioning as a union type.
Applying this concept to your provided example:
enum Enum {
EnumValueA,
EnumValueB
}
interface interfaceX { a: string, b: Enum }
const x: interfaceX = { a: 'mango', b: Enum.EnumValueA }
const y: Enum = Enum.EnumValueA
x.b = y
// With Enum as a union enum, flow analysis and logic checks mirror those of regular union types:
function f(arg1: Enum) {
if (arg1 !== Enum.EnumValueA || arg1 !== Enum.EnumValueB) {
// Error message regarding comparison being unintentional due to non-overlapping types.
}
}
To allow assignment or passing of strings (e.g., 'EnumValueA'
) instead of specific enum references (Enum.EnumValueA
), utilize the following approach:
// The type of arg1 will be: 'EnumValueA' | 'EnumValueB'
function f2(arg1: keyof typeof Enum) {
// perform actions
}
f2('EnumValueA')