0

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

2
  • 2
    Yes, these checks don't work in TS. You need to check a variable, e.g., const myThing = state[id]; if (myThing) { myThing.apple.status = "ripe"; } Commented Oct 16, 2021 at 9:03
  • Did My answer solved your problem? Commented Oct 18, 2021 at 12:01

2 Answers 2

1

You can use ! typescript ignores the fact that the value could be undefined which in your case is not

state[hello]!.apple.status = "ripe";
Sign up to request clarification or add additional context in comments.

Comments

1

Use any of these instead of checking with just state['hello']

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

3 Comments

"if (state['hello']) will always be true." not, if the property is missing, or the value is falsy then the if will not trigger.
if (!!state['hello']) is exactly the same as if (state['hello'])
Also, state['hello'] !== undefined (you have missing d at the end) will only work if the key is either missing or set to undefined, not if it's any other falsy value. Most notably null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.