Typescript optional chaining combined with ternary operator parsing error

Viewed 1139

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 Answers

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>
Related