Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript optional chaining combined with ternary operator parsing error

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?

like image 363
Jordan Avatar asked Dec 07 '25 10:12

Jordan


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>
like image 77
Erik Avatar answered Dec 10 '25 01:12

Erik