3

I'm having trouble using Typescript optional chaining in conjunction with the ternary operator inside of a React component. I'm not sure if it can't be done, my syntax is off, or it is a Typescript bug.

Note that in my particular case I need to use bracket notation to access an object's key, while in the examples I give you technically don't.

Without optional chaining:

import * as React from "react"

const Component: React.FC<{}> = () => {
  const test = {
    key1: {
      key2: Math.random() === 0 ? null : {
        key3: "3"
      }
    }
  }

  return(
    <div>
      {test["key1"]["key2"]["key3"] ? "Key3 Exists" : "Key3 Doesn't Exist" } {*/ Error: Object test["key1"]["key2"] is possibly null. */}
    </div>
  )
}

With optional chaining

import * as React from "react"

const Component: React.FC<{}> = () => {
  const test = {
    key1: {
      key2: Math.random() === 0 ? null : {
        key3: "3"
      }
    }
  }

  return(
    <div>
      {test["key1"]["key2"]?["key3"] ? "Key3 Exists" : "Key3 Doesn't Exist" } {*/ Error: ":" expected. */}
    </div>
  )
}

The typescript compiler appears to think that the question mark after ["key2"] in the second example is starting a ternary operation.

Anyone know how to use them both together?

1
  • The documentation clearly describes how to use optional chaining with bracket notation. This has nothing to do with the conditional operator. Commented Feb 9, 2021 at 8:22

1 Answer 1

6

The syntax for optional chaining does not only consist of the question mark, but actually also the adjacent dot. Your code should work better like this:

<div>
      { test?.["key1"]?.["key2"]?.["key3"] ? "Key3 Exists" : "Key3 Doesn't Exist" }
    </div>
Sign up to request clarification or add additional context in comments.

Comments

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.