TS 3.7 beta 版发布了,引入了Optional Chaining TypeScript

1,072 阅读1分钟

如何使用

npm install typescript@beta

重磅新功能

1, 引入了Optional Chaining 可选链

那么什么是可选链?我们知道,访问对象属性时,若此属性的值为null或undefined,在使用. 操作,就会报错,如下

let x = a.b.c;

若a的值为null或undefined,上述表达值会报错,我们的常用写法为 
let x = a && a.b && a.b.c
为了解决这个问题

所以 引入了?. 操作符,如下:

let x = a?.b.c;
若a的值为null或undefined,x 为 undefined;

2, Null 判断运算符

当我们使用某个变量的时候,要为其制定默认值,最为方便的是 || ,如下:
let a = b || c;
当 b 的值转换为 boolbean 为true时,a=b ,否则,a=c;

所以 引入了?? 运算符
let a = b ?? c;
当 b === null 或者 b === undefind 时,a = c;