乐闻世界logo
搜索文章和话题

What does exclamation point after variable mean in TypeScript?

1个答案

1

In TypeScript, the exclamation mark (!) after a variable is a non-null assertion operator. This operator informs the TypeScript compiler that the developer has confirmed the variable will not be null or undefined when used, even though the type system might allow it to be null or undefined. This is commonly used when developers can guarantee a value will be assigned, but TypeScript's type checking might not infer this. Using the non-null assertion operator can prevent compilation errors.

Example

Assume we have an interface User and a function getUserById that might return User or null:

typescript
interface User { id: number; name: string; } function getUserById(id: number): User | null { // Simulate user data retrieval if (id === 1) { return { id: 1, name: 'Alice' }; } return null; } const user = getUserById(1); console.log(user!.name); // Alice

In this example, although getUserById returns User | null, meaning user could be null, the implementation ensures it returns a User object when called with 1. Therefore, the ! suffix tells the TypeScript compiler that user is not null in this context, enabling safe access to user.name without compilation errors.

However, overusing the non-null assertion operator can lead to runtime errors, as it instructs the compiler to ignore null checks. If used inappropriately when the variable is actually null or undefined, accessing its properties or methods at runtime will cause errors. Thus, it is recommended to use this operator only when you can guarantee the variable is not null or undefined.

2024年6月29日 12:07 回复

你的答案