假设有一个
enum ArrowKey{
Up = "ArrowUp",
Right = "ArrowRight",
Down = "ArrowDown",
Left = "ArrowLeft"
}
现在,当接收到带有 e.key
“ArrowUp”的 KeyboardEvent
时,如何轻松检查该字符串值是否存在于枚举中?以及之后如何选择正确的枚举值?
最佳答案
以下函数将返回对应于按下的箭头键的枚举值,如果该键未在该枚举中定义,则返回 null。
getEnumValue(event): ArrowKey | null {
const pressedKey = event.key;
const keyEnum = Object.keys(ArrowKey).find(key => ArrowKey[key] === pressedKey);
return ArrowKey[keyEnum] || null;
}
演示:https://stackblitz.com/edit/angular-dmqwyf?embed=1&file=app/app.component.html
编辑:相当于一行(ES 2017)
getEnumValue(event): ArrowKey | null {
return Object.values(ArrowKey).includes(event.key) ? event.key : null;
}
关于typescript - 检查枚举 TypeScript 中的字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49072376/