Home > front end >  Checking if object is undefined with variable does not work Typescript
Checking if object is undefined with variable does not work Typescript

Time:10-17

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?

See typescript playground

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']

  1. !!state['hello']
  2. state['hello'] !== undefined
  • Related