Optional Chaining 解决的问题是重复且无心义的判空,之因此说无心义,是对业务来讲它不是必需的,但不判空,程序直接就挂了,好比:git
let x = foo.bar.baz();
这里的访问链路上 foo
bar
baz
任何一个为 undefined
,程序就中止工做。github
使用 Optional Chaining 修改后:json
let x = foo?.bar.baz();
这里 ?.
的句法就是 Optional Chaining,在 TypeScript 3.7 中实现,目前 tc39 提案中处于 Stage 4 阶段。数组
Optional Chaining 在这里表示,若是 foo
是 null
或 undefined
,整个语句不继续日后执行,直接返回 undefined
。async
做用范围
须要注意的是,这里只对 foo
进行了保障,若是后续的 bar
,baz
为空的话,代码仍然报错。?.
只做用于左边的对象。fetch
因此能够这样来修正:ui
let x = foo?.bar?.baz();
这样能够保障 foo
bar
为空的状况下不报错。这体现了 optional property accesses
的功能。url
Opptoinal call
对于方法也一样适用。spa
async function makeRequest(url: string, log?: (msg: string) => void) { log?.(`Request started at ${new Date().toISOString()}`); // roughly equivalent to // if (log != null) { // log(`Request started at ${new Date().toISOString()}`); // } const result = (await fetch(url)).json(); log?.(`Request finished at at ${new Date().toISOString()}`); return result; }
Optional element access
数组也是对象,只不是特殊的对象,经过数字索引做为属性来访问。因此 Optional Chaining 也可做用于数组元素的访问,此时就体现了 optional element access
的功能,请看来自官方文档中的示例:郑州妇科医院哪里好http://www.zztjfkyy.com/.net
/** * Get the first element of the array if we have an array. * Otherwise return undefined. */ function tryGetFirstElement<T>(arr?: T[]) { return arr?.[0]; // equivalent to // return (arr === null || arr === undefined) ? // undefined : // arr[0]; }
和 &&
的差异
虽然说 Optional Chaining 取代了以下经过 &&
来实现的判空操做:
// Before if (foo && foo.bar && foo.bar.baz) { // ... }
但 Optional Chaining 和 &&
仍是有区别,后者利用 JavaScript 中的短路机制,遇到假值时中断执行。而前者只会在被断定对象为 null
或 undefined
时才会中断执行。
请看以下示例:郑州看妇科医院哪家好http://www.zztongjifk.com/
const a: any = 0; console.log(a?.blah); console.log(a && a.blah); const b: any = false; console.log(b?.blah); console.log(b && b.blah); const c: any = ""; console.log(c?.blah); console.log(c && c.blah);
输出:
undefined 0 undefined false undefined
能够看到,经过 Optional Chaining 控制的部分所有输出 undefined
,由于这里被断定对象并非 null
或 undefined
,因此语句会日后执行,尝试访问 blah
,拿到的值是 undefined
,最后输出。
而经过 &&
进行断定的语句,由于被断定对象是假值,中断执行并返回当前对象。
Nullish Coalescing
Nullish Coalescing 经过 ??
操做符,为 null
或 undefined
的值提供默认值。
好比:
let x = foo ?? bar();
上面的表达式等价于若是 foo
是 null
或 undefined
,则调用 bar()
。
一样地,他取代了以前经过 ||
操做符达到的默认值效果,但后者一样是经过判断布尔真值达到的,而 Nullish Coalescing 只判断 null
或 undefined
。
好比:郑州妇科医院哪家好http://www.zzyytj.com/
function initializeAudio() { let volume = localStorage.volume || 0.5; // ... }
这里若是 localStorage.volume
被设置成 0,则最后 volume
获得的是 0.5,也就是说设置在 localStorage.volume
永远也不会生效。而 Nullish Coalescing 就能够避免这种问题。