在TypeScript中,"??" 是一个逻辑运算符,称为"nullish coalescing"(空值合并)运算符。它用于判断一个值是否为 null 或 undefined,并在其为真时返回一个默认值。
使用 "??" 运算符可以简化对变量是否为 null 或 undefined 的判断。例如:
const foo = null;
const bar = foo ?? "default value";
console.log(bar); // 输出 "default value"
在上面的例子中,如果 foo
是 null 或 undefined,那么 bar
将被赋值为 "default value"。否则,bar
将被赋值为 foo
的值。
需要注意的是,"??" 运算符只会在左侧的值为 null 或 undefined 时返回默认值,而不会在左侧的值为其他“假值”(如空字符串、0、false 等)时返回默认值。
--------------
在TypeScript中,"!" 和 "?" 是两个不同的运算符。
"!" 运算符是非空断言运算符(non-null assertion operator),用于告诉编译器一个变量一定不会是 null 或 undefined。它用于在编译时排除可能的空值错误。但是需要注意,滥用非空断言运算符可能会导致运行时错误,因此应该谨慎使用。
例如:
const foo: string | null = null;
const bar: string = foo!; // 使用非空断言运算符
console.log(bar); // 编译通过,但会在运行时抛出错误
在上面的例子中,我们使用非空断言运算符告诉编译器 foo
不会是 null 或 undefined,但实际上它的值确实为 null,因此在运行时会抛出错误。