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?
}
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'
try
function Convert (rowState: RowStates): RowColors {
return RowColors[RowStates[rowState]];
}
working example here
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With