先看下TypeScript基础之非空断言操作符、可选链运算符、空值合并运算符-CSDN博客
我没有复现出来,但是我知道了它的作用
用 let str: string = arg!;
代替
let str: string;
if (arg) { str = arg; }
非空断言(!
)和不使用的区别在于对于可能为 null
或 undefined
的值的处理方式。非空断言告诉 TypeScript 编译器在某个特定上下文中,你确定一个值不会为 null
或 undefined
。
下面是一个示例代码,演示了使用非空断言和不使用的区别:
// 使用非空断言
function withNonNullAssertion(input: string | null): void {let length: number = input!.length; // 使用非空断言console.log(length);
}// 不使用非空断言
function withoutNonNullAssertion(input: string | null): void {if (input !== null) {let length: number = input.length; // 不使用非空断言,通过条件检查console.log(length);} else {console.log('Input is null');}
}// 示例调用
let myString: string | null = 'Hello, TypeScript!';
withNonNullAssertion(myString); // 使用非空断言
withoutNonNullAssertion(myString); // 不使用非空断言
在 withNonNullAssertion
函数中,我们使用非空断言直接获取 input
的长度,因为我们在这个上下文中确切地知道 input
不会为 null
。这样做可以简化代码,但要确保你在使用非空断言时了解上下文,并且确定该值确实不会为 null
或 undefined
。
在 withoutNonNullAssertion
函数中,我们通过条件检查确保 input
不为 null
,然后再使用它的属性。这是一种更安全的方式,适用于在某些情况下你不能确定值是否为 null
或 undefined
的情况。