ts-enum-mapper
TypeScript icon, indicating that this package has built-in type declarations

1.5.0 • Public • Published

ts-enum-mapper

ts-enum-mapper makes it easy to have one-to-one relationships between an enum and a set of values.

I.e. instead of an exhaustive switch with a case-per-value and an assertNever, you can do one-line-per-value and still get the benefits of type-checking (because the compiler will enforce that your mapping definition has a key for each enum value):

enum Color {
  Red = 'RED',
  Blue = 'BLUE',
  Green = 'GREEN',
}
 
const mapping = mapEnum(Color, {
  Red: 'red!',
  Blue: 'blue!',
  Green: 'green!',
});
 
expect(mapping.map(Color.Red)).toEqual('red!');
expect(mapping.parse('red!')).toEqual(Color.Red);

Instead of the more traditional:

function mapColor(color: Color) {
  switch (color) {
    case Color.Red:
      return 'red!';
    case Color.Blue:
      return 'blue!';
    case Color.Green:
      return 'green!';
    default:
      return assertNever(color);
  }
}

Readme

Keywords

none

Package Sidebar

Install

npm i ts-enum-mapper

Weekly Downloads

139

Version

1.5.0

License

Apache-2.0

Unpacked Size

391 kB

Total Files

136

Last publish

Collaborators

  • shaberman