如何检查给定的字符串键是否存在于枚举中? [英] How to check if a given string key exists in Enum?

查看:37
本文介绍了如何检查给定的字符串键是否存在于枚举中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的枚举:

I have an enum defined like this:

export enum someEnum {
    None = <any>'',
    value1 = <any>'value1',
    value2 = <any>'value2',
    value3 = <any>'value3'   
}

例如,我想检查value4";键存在于枚举中.我应该得到 false 因为 value4 没有在 enum 上定义.

For example, I want to check "value4" key exists in an enum. I should get false as value4 is not defined on the enum.

我尝试了 if (someEnum['value4']) 但出现错误:

I tried if (someEnum['value4']) but got an error:

元素隐式具有any"类型,因为索引表达式不是number"类型.

Element implicitly has an 'any' type because index expression is not of type 'number'.

推荐答案

您可以使用 in 运算符:

You could use the in operator:

if ('value4' in someEnum) {
  // ...
}

这篇关于如何检查给定的字符串键是否存在于枚举中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆