TypeScript对象解构的可选链

3

我刚刚升级了 typescript3.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.
  ...
}

我想在使用 解构赋值 时使用 可选链

这个功能现在可用吗?

1个回答

9

这是因为queryStringParameters可能为空,而null对象不包含属性no。您需要使用null合并运算符来解决:

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

请注意,?? 运算符目前只能在 TypeScript 3.7+ 中使用,截至目前还不是标准的 JS 运算符。有关更多详细信息,请参阅 TypeScript 存储库上的相关讨论:https://github.com/microsoft/TypeScript/issues/26578


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接