Converting one Enum to another in JavaScript

问题: I have two enums with the same keys but different values. enum RowStates { editing = 0, sentToApproval, approved // ... } enum RowColors { editing =...

问题:

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

回答1:

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) {
    return RowColors[RowStates[rowState]];
}

console.log(convert(RowStates.sentToApproval)); // prints '#ffffcc'

回答2:

try

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

working example here

  • 发表于 2019-03-19 06:27
  • 阅读 ( 196 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除