Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting one Enum to another in JavaScript

EDIT

As comment suggests, Enum is not part of JavaScript but part of TypeScript. I intentionally left original title as one may make mistake like me.


I have two enums with the same keys but different values.

enum RowStates {
    editing = 0,
    sentToApproval,
    approved
    // ...
}

enum RowColors {
    editing = '#ffffff',
    sentToApproval = '#ffffcc',
    approved = '#ccffb3'
    // ...
}

And I have some function to do convertion:

function Convert (rowState) {
// What should be here to return rowColor?
// Using switch (rowState) is obvious, but may be other solution exist?
}
like image 513
Fyodor Avatar asked Jan 27 '23 14:01

Fyodor


2 Answers

TypeScript enums allow you to do a reverse mapping:

enum RowStates {
    editing = 0,
    sentToApproval,
    approved
}

enum RowColors {
    editing = '#ffffff',
    sentToApproval = '#ffffcc',
    approved = '#ccffb3'
}

function convert(rowState: RowStates) {
    return RowColors[RowStates[rowState] as keyof typeof RowColors];
}

console.log(convert(RowStates.sentToApproval)); // prints '#ffffcc'
like image 148
Robby Cornelissen Avatar answered Jan 29 '23 04:01

Robby Cornelissen


try

function Convert (rowState: RowStates): RowColors {
    return RowColors[RowStates[rowState]];
}

working example here

Update

As poloapolo notice in his comment in current TS 4.5.2 version (and probably in some earlier versions too) this solution produce linter error

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof RowColors

it can be avoid as follows (this is alternative to Robby answer)

function Convert (rowState: RowStates): RowColors {
  return new Map(Object.entries(RowColors)).get(RowStates[rowState]) as RowColors
}

In both solutions we can add some kind of validation in case when there is key in RowStates which not exists in RowColors

like image 36
Kamil Kiełczewski Avatar answered Jan 29 '23 04:01

Kamil Kiełczewski