#Key in Enum?

18 messages · Page 1 of 1 (latest)

tawdry oracleBOT
#

@tranquil vector Here's a shortened URL of your playground link! You can remove the full link from your message.

Azat S.#0801

Preview:```ts
// imported module

enum Animals {
Dog = 'Dog',
Cat = 'Cat',
Mouse = 'Mouse'
}

let animal = 'Cat' as Animals

// my module

let myName: string = ''

let names = {
[Animals.Dog]: 'Dog',
[Animals.Cat]: 'Cat'
}

if (animal in names) {
myName = names[animal]
...```

ripe quartz
#

That's not a bug, the problem is that animal could be Dog | Cat | Mouse, and names could have the property [Animals.Mouse] but nobody told the compiler about it

#

so it could be [Animals.Mouse]: 4000

#

which, if typescript didn't throw an error, would be equivalent to
let myName: string = 4000

#

which is a type error

#

does that make sense?

tranquil vector
#

Okay. But how can I fix it?

Only like this?

if (animal === Animals.Dog) {
  myName = Animals.Dog
} else if (animal === Animals.Cat) {
  myName = Animals.Cat
}  // ....
ripe quartz
#

yep or use a switch

#

or just tell typescript to go for it

tranquil vector
#

Sounds sad. Thank you

ripe quartz
#
myName = names[animal as never]

but that turns off the type-system

ripe quartz
#

in this specific instance where we can see that names was just created and nothing modifies it, it's easy to prove safe

#

but that's a rare set of circumstances.

#

@tranquil vector another way to deal with it

#

is to derive the type of animal from valid keys of names

tawdry oracleBOT
#
webstrand#8856

Preview:ts ... let animal = "Cat" as keyof typeof names ...