类型操作符
非空断言、可选链、空值合并分别怎么写?
// 非空断言, 告诉编译器 map 一定有值
map!;
// 可选链, map 非空时执行 getLayer(), 为空时返回 undefined
map?.getLayer();
// 空值合并, 左侧为 null 或 undefined 时返回右侧, 否则返回左侧
const foo = null ?? "default string";
!: 从类型中移除null与undefined, 不做运行期检查;?.: 遇到null或undefined时短路, 整个表达式返回undefined;??: 只在左侧为null或undefined时取右侧;
空值合并与逻辑或有什么区别?
||: 左侧为任何假值时都取右侧,0、""、false会被替换掉;??: 只把null与undefined视为空, 其余假值原样保留;
0 || 5; // 5
0 ?? 5; // 0