【问题标题】:typescript optional chaining with object destructuring带有对象解构的打字稿可选链接
【发布时间】:2023-03-07 03:14:01
【问题描述】:

我刚刚将typescript 更新为3.7.4,我正在尝试编辑我的代码。

我有一个简单的代码

interface Test
  event: {
    queryStringParameters: { [name: string]: string } | null;
  }
}
const test:Test = (event) => {
  // const { no } = event?.queryStringParameters; //Property 'no' does not exist on type '{ [name: string]: string; } | null'.ts(2339)
  const no = event?.queryStringParameters?.no; //It works but I want to use above that.
  ...
}

我想将optional chainingdestructuring 一起使用。

现在有这个功能吗?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    那是因为 queryStringParameters 可以为 null,而 null 对象不包含属性 no。为此,您需要使用null coalescing operator

    const { no } = event?.queryStringParameters ?? { no: null };
    

    请注意,?? 运算符目前只能通过 TypeScript 3.7+ 使用,目前还不是标准的 JS 运算符。有关详细信息,请参阅 TypeScripts repo 的相关讨论:https://github.com/microsoft/TypeScript/issues/26578

    【讨论】:

      猜你喜欢
      • 2019-12-12
      • 2021-07-22
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 2018-05-26
      • 1970-01-01
      • 2020-08-10
      相关资源
      最近更新 更多