Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

typescript - How to check if a given string key exists in Enum?

I have an enum defined like this:

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

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use the in operator:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...