#Accessing const object value by unknown key?

13 messages · Page 1 of 1 (latest)

rocky lion
#

I've got a string coming in off of a query parameter and I can't figure out how to coerce it into one of my known FooBar values. I can't access FooBar by any string and I'm not sure what to do to get around that.

This would normally be used like FooBar.Foo or .Bar

leaden grail
#

check if it's in FooBar

rocky lion
celest oreBOT
#
claudekennilol#0

Preview:```ts
console.clear()

declare type FooBar =
typeof FooBar[keyof typeof FooBar]

const FooBar = {
Foo: "foo",
Bar: "bar",
} as const

const fooz: any = "foo"
const nope: any = "nope"

if (fooz in FooBar) {
console.log(`'${fooz}' is in FooBa
...```

rocky lion
#

Gives this output

[LOG]: "'foo' is NOT in FooBar" 
[LOG]: "'nope' is NOT in FooBar" 
[LOG]: "shouldBeFoo",  undefined 
[LOG]: "shouldBeUndefined",  undefined 
leaden grail
#

well foo isn't in FooBar, Foo is

#

hmm wait in checks narrow the rhs, so while this would work at runtime, it wouldn't give you the right types

rocky lion
#

Good point. I guess I need to verify the value is there and not the key 🙃

leaden grail
#

i don't remember the idiomatic way to check for that in ts, unfortunately.

rocky lion
#

Now that it was pointed out I need to verify the value and not fetch by key, this works 🙃

Object.values(FooBar).includes(fooz) ? fooz as FooBar : undefined;
leaden grail
#

wait are you trying to check if it's actually one of the values? i kinda skimmed before and assumed you meant keys

rocky lion
leaden grail
#

ah, it's an enum replacement