How can I handle non-existing object properties in TypeScript?
In the scenario below, TypeScript raises an error for fooBar[foo]
-
Element implicitly has an 'any' type because expression of type '"fooBar"' cannot be used to index type '{ readonly foo: "bar"; readonly bar: "foo"; }'.
Property 'fooBar' does not exist on type '{ readonly foo: "bar"; readonly bar: "foo"; }'
What is the most appropriate way in TypeScript to address this issue?
const fooBar = {
foo: 'bar',
bar: 'foo'
} as const
const foo: 'foo' | 'fooBar' = 'fooBar';
const op: 'foo' | "bar" | 'default' = fooBar[foo] || 'default';