Hi there?
Could you help me please. How can I fix this problem?
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
18 messages · Page 1 of 1 (latest)
Hi there?
Could you help me please. How can I fix this problem?
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
@tranquil vector Here's a shortened URL of your playground link! You can remove the full link from your message.
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]
...```
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?
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
} // ....
Sounds sad. Thank you
myName = names[animal as never]
but that turns off the type-system
it's not safe, what you're trying to do, in general
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