I want to access a key in an object, but of course before doing so I need to check if the object is defined first. This works if I reference the key with a string, but typescript yells if I reference it with a variable assigned with a string:
type Fruit = "apple" | "orange";
type State = {
[id in string]?: {
[fruit in Fruit]: {
status: "ripe" | "rotten";
};
};
};
const state: State = {};
const id = "hello";
if (state[id]) {
state[id].apple.status = "ripe";
^^^^^^^^^
Object is possibly 'undefined'.(2532)
}
if (state["hello"]) {
// This is perfectly OK
state["hello"].apple.status = "ripe";
}
Why is this?
CodePudding user response:
You can use !
typescript ignores the fact that the value could be undefined which in your case is not
state[hello]!.apple.status = "ripe";
CodePudding user response:
Use any of these instead of checking with just state['hello']
- !!state['hello']
- state['hello'] !== undefined