#Why enum key can index a const object while a string instance can't?

3 messages · Page 1 of 1 (latest)

novel jasper
#

Look at this Playground snippet: I can index the const object with an enum instance, as long as the value of the instance is a key in the const object; but I can't index it with a string instance.

I do understand why a string instance can't be used to index the const object, even if the value of the instance is a key in the object, but why using an enum key works?

proven schoonerBOT
#

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

noctisshadowzel#0

Preview:```ts
const fooMap = {
fooKey: "fooVal",
barKey: "barVal",
bazKey: "bazVal",
} as const

enum FooKey {
FooKey = "fooKey",
BarKey = "barKey",
BazKey = "bazKey",
ZaaKey = "zaaKey",
}

const key = FooKey.BarKey

console.log(fooMap[key])
console.log(fooMap[FooKey.BazKey])
...```

keen locust
#

because FooKey is a more specific type than string. it's more like if you did this: