跳到主要内容

类型操作符

非空断言、可选链、空值合并分别怎么写?​

// 非空断言, 告诉编译器 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