DEV Community

loading...

Discussion on: Managing Key-Value Constants in TypeScript

Collapse
constjs profile image
Piotr Lewandowski • Edited

Nice replacements for enums.
Example can be improved a bit to avoid duplications (everything is calculated based on colorLabels):

export const colorLabels = {
  green: 'Green',
  red: 'Red',
  blue: 'Blue',
} as const;

type ColorID = keyof typeof colorLabels;

export const colorIDs = Object.keys(colorLabels) as ColorID[];
Collapse
lacolaco profile image
Suguru Inatomi Author

Thank you! I agree on it is simpler than I posted version.
In other hand, I think the ordering is important in this usecase. Object fields is easily sorted by code editing so it is not safe to keep the ordering.
This is why I want to manage IDs as a tuple. How do you think?

Collapse
briancodes profile image
Brian • Edited

Object.keys(colorLabels) keeps the order that the keys were added to the object. The object can't be edited after it's created as you've used const ... as const, so I think it's safe