在 TypeScript 中访问对象属性时,运算符 !(感叹号)是什么意思?
大家好!我最近开始学习 TypeScript,遇到了一个我不理解的构造。在同事的代码中,我看到了在变量后或访问对象属性前使用感叹号的情况。例如:
```typescript
const userName: string | null = getUserName();
const length = userName!.length;
```
或者这样:
```typescript
interface User {
name?: string;
email?: string;
}
function getUserEmail(user: User): string {
return user.email!;
}
```
我理解 `?` 表示可选值(可能是 undefined 或 null)。但 `!` 是做什么的?这是某种强制访问运算符吗?如果值实际上是 null 或 undefined,它会不会在运行时导致错误?
我尝试过搜索,但到处都写着“non-null assertion operator”。老实说,听起来有点吓人。你能用简单的话解释一下它是如何工作的,以及何时安全使用它吗?
提前感谢你的帮助!