Issue
I have the following two enums in separate files:
// Variant.ts
export enum Variant {
LINK = "link",
LINK_OUTLINE = "linkOutline",
ICON_ONLY = "iconOnly",
}
// ButtonEditType.ts - derived from above one
export enum ButtonEditType {
ICON_ONLY = Variant.ICON_ONLY,
ICON_TEXT = Variant.LINK,
ICON_TEXT_OUTLINE = Variant.LINK_OUTLINE,
}
// printing the enum in the file where I imported it
console.log(ButtonEditType);
Here, the console.log
above should normally print -
{
"ICON_ONLY": "iconOnly",
"ICON_TEXT": "link",
"ICON_TEXT_OUTLINE": "linkOutline"
}
But, instead I get -
{
"ICON_ONLY": "iconOnly",
"iconOnly": "ICON_ONLY",
"ICON_TEXT": "link",
"link": "ICON_TEXT",
"ICON_TEXT_OUTLINE": "linkOutline",
"linkOutline": "ICON_TEXT_OUTLINE"
}
Live snippet - https://stackblitz.com/edit/stackblitz-starters-eyycla
I've 2 possible solutions -
- to make all the properties of
ButtonEditType
as plain strings instead of referencing fromVariant
- to keep both enums in same file
but I can't use both of them because I want to make things consistent with my Project
Can anyone please help me understand what's wrong when an enum is referenced from another file?
Solution
Typescript generates reverse mappings at compile time for computed members but not constant members. Moving Variant
to another file changes the nature of its values from constant to computed.
I suggest you use const assertions instead of enums if you wish to print out the values, as it has the same effect as enum without the extra reverse mappings.
import { Variant } from './Variant';
export const ButtonEditType = {
ICON_ONLY: Variant.ICON_ONLY,
ICON_TEXT: Variant.LINK,
ICON_TEXT_OUTLINE: Variant.LINK_OUTLINE,
} as const;
Here's an answer comparing string enums to const-asserted object.
Answered By - alexwbt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.