Home > Blockchain >  Why is `id` ignored by an enum in Typescript?
Why is `id` ignored by an enum in Typescript?

Time:05-17

I ran into an issue with my app earlier today, when I was trying to conditionally render elements based on whether or not a value exists in an enum. Here is the simplified code:

enum Enum {
    'id',
    'name',
    'age'
}

['id', 'name', 'age'].forEach((val) => {
    console.log('in enum: ', !!Enum[val])
})

This prints,

"in enum: ",  false 
"in enum: ",  true 
"in enum: ",  true 

I ended up doing something like,

. . .
if (!!Enum[val] && val === 'id') {
    // code
}
. . .

Am I missing something? Is id some sort of reserved value for enums?

CodePudding user response:

By doing !!Enum[val] you're testing enum value not enum key:

console.log(!!0) //prints false
console.log(!!1) //prints true
console.log(!!2) //prints true

Your code should look like this:

['id', 'name', 'age'].forEach((val: any) => {
    console.log('in enum: ', (val in Enum))
})

CodePudding user response:

id, name, age it is NOT values. It's KEYS for default valuses. Example: enum Enum { 'id = 0','name = 1', 'age = 2' } - it is default valuses. You by KEY asks for a VALUE

For example:

    enum Enum {
        'id' = 'a',
        'name' = 'b',
        'age' = 'c'
    }
    
    ['id', 'name', 'age'].forEach((val: any) => {
        console.log('in enum: ', Enum[val])
    })
    // result -> a, b, c
  • Related