#Accessing const object value by unknown key?
13 messages · Page 1 of 1 (latest)
check if it's in FooBar
And that looks like what?
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
...```
Gives this output
[LOG]: "'foo' is NOT in FooBar"
[LOG]: "'nope' is NOT in FooBar"
[LOG]: "shouldBeFoo", undefined
[LOG]: "shouldBeUndefined", undefined
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
Good point. I guess I need to verify the value is there and not the key 🙃
i don't remember the idiomatic way to check for that in ts, unfortunately.
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;
wait are you trying to check if it's actually one of the values? i kinda skimmed before and assumed you meant keys
Yeah I think I misstated the problem then confused myself as to what I actually needed
ah, it's an enum replacement