A better way for TypeScript Enum

A better way to define enums in Typescript

const ORDER_STATUS = {
  OPEN: 'Offen',
  ORDERED: 'Bestellt',
  CANCELED: 'Storniert'
} as const;

type OrderStatus = keyof typeof ORDER_STATUS;

function methodWithEnum(status: OrderStatus) {
    console.info(`${ORDER_STATUS[status]}: ${status}`);
}

methodWithEnum("OPEN");

In this way it is much easier to provide an enum including a potential mapping to a different value e.g. a display value.

This solution is usually considered being better, as long as enums aren’t supported by JavaScript natively.

Links

Paul Sterl has written 54 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>