簡體   English   中英

Typescript 可選鏈結合三元運算符解析錯誤

[英]Typescript optional chaining combined with ternary operator parsing error

我在將 Typescript 可選鏈接與 React 組件內部的三元運算符結合使用時遇到問題。 我不確定它是否無法完成,我的語法已關閉,或者它是 Typescript 錯誤。

請注意,在我的特定情況下,我需要使用括號表示法來訪問對象的鍵,而在我給您的示例中,技術上不需要。

沒有可選鏈接:

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>
  )
}

帶有可選鏈接

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>
  )
}

typescript 編譯器似乎認為第二個示例中["key2"]之后的問號正在啟動三元運算。

有人知道如何同時使用它們嗎?

可選鏈接的語法不僅包含問號,實際上還包含相鄰的點。 您的代碼應該像這樣更好地工作:

<div>
      { test?.["key1"]?.["key2"]?.["key3"] ? "Key3 Exists" : "Key3 Doesn't Exist" }
    </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM