使用可选的链接运算符访问对象属性

TypeScript 3.7现在支持 可选链接操作符,因此,您可以编写以下代码:

const value = a?.b?.c;

I.e., you can use this operator to access properties of an object, where the object itself may be null or undefined. Now what I would like to do is basically the same, but the property names are dynamic:

const value = a?[b]?.c;

然而,我得到了一个语法错误:

错误 TS1005: “ :”预期。

我到底做错了什么,这有可能吗?

建议书似乎暗示这是不可能的(但也许我把语法示例弄错了)。

21293 次浏览

When accessing a property using bracket notation and optional chaining, you need to use a dot in addition to the brackets:

const value = a?.[b]?.c;

这是 TC39 proposal采用的语法,否则解析器很难判断这个 ?是三元表达式的一部分还是可选链接的一部分。

我是这么想的: 可选链接的符号不是 ?,而是 ?.。如果使用可选的链接,则始终使用两个字符。

可选链接运算符是 ?.

下面是可空属性和函数处理的一些示例。

const example = {a: ["first", {b:3}, false]}


// Properties
example?.a  // ["first", {b:3}, false]
example?.b  // undefined


// Dynamic properties ?.[]
example?.a?.[0]     // "first"
example?.a?.[1]?.a  // undefined
example?.a?.[1]?.b  // 3


// Functions ?.()
null?.()                // undefined
validFunction?.()       // result
(() => {return 1})?.()  // 1

奖励: 默认值

如果未定义或为空,可以使用 ??(NullishCoalesching)设置默认值。

const notNull = possiblyNull ?? defaultValue
const alsoNotNull = a?.b?.c ?? possiblyNullFallback ?? defaultValue