gpt4 book ai didi

typescript - 检查枚举 TypeScript 中的字符串值

转载 作者:搜寻专家 更新时间:2023-10-30 21:28:12 26 4
gpt4 key购买 nike

假设有一个

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com