繁体   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