Iteration string with no enum

Viewed 24

In Typescript, enum is regarded as not recommended to use because it makes cost of compiled javascript code bigger. And its alternative is string literal union.

But I often face the situation of having to iterate specific literals, or to use string literal with way of enum.

E.G. In JSX, writing like <Component type={Type.A} /> enables to take advantage of the feature of IDE(e.g. IntelliJ's "Refactor Name"(Shift + F6)), but not <Component type="A" />

So, I have been making indirect enum object and using it.

type Type = 'A' | 'B' | 'C';
type EnumObject<T extends keyof any> = { [K in T]: K };

// Unfortunately, "Refactor Name" feature of IntelliJ does not work perfectly
const TypeEnum: EnumObject<Type> = {
  A: 'A',
  B: 'B',
  C: 'C',
};

// iteration
Object.values(TypeEnum).map( ~ );

// using like enum
<Component type={TypeEnum.A} />

But I wonder whether this is the right way. Is giving up the convenience of enum because of its cons and making separate "enum object" is worth that much?

0 Answers
Related