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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With