最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Converting one Enum to another in JavaScript - Stack Overflow

programmeradmin3浏览0评论

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?
}

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?
}
Share Improve this question edited Mar 24, 2019 at 10:23 Fyodor Yemelyanenko asked Mar 18, 2019 at 3:48 Fyodor YemelyanenkoFyodor Yemelyanenko 11.8k2 gold badges32 silver badges40 bronze badges 1
  • 7 emun is not a javascript keyword. – Maheer Ali Commented Mar 18, 2019 at 3:48
Add a comment  | 

2 Answers 2

Reset to default 15

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

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

发布评论

评论列表(0)

  1. 暂无评论