假设我有两个枚举Side
和SideDecider
,在后一个枚举中,我有一个密钥side
,其值应为Side
,这样当我使用SideDecider.side
,我知道它是Side
的值。
enum Side {
left,
right,
}
enum SideDecider {
random,
other,
side, // = Side.left | Side.right is what I would like to use
}
// I am looking for a solution resolving something like the following to true
console.log(Side.left === SideDecider.side || Side.right === SideDecider.side)
// error: This condition will always return 'false' since the types 'Side.left' and 'SideDecider.side' have no overlap.
我将如何正确产生这种用法。我是否要错误地使用enums
?谢谢您的提前帮助。
Check out example at TypeScript Playground
编辑
我实际上想要实现的目标是相同的,只是使用enums
作为字符串,因此我可以将它们用作对象的键,请参见my second example。 Here,有人建议为基于字符串的枚举使用一个类。这是最佳做法吗?
enum Side {
left = 'left',
right = 'right',
}
enum SideDecider {
random = 'random',
other = 'other',
side = Side.left | Side.right // Error: Computed values are not permitted in an enum with string valued members
}
const testObj = {
left: 'something',
right: 'something',
}
// (1) I am looking for a solution resolving something like the following to [true, true]
console.log([Side.left && SideDecider.side, Side.right && SideDecider.side])
// (2) Is there a way to use SideDecider.side to access keys in testObj?
console.log(testObj[SideDedicer.side])