问题:
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