In TypeScript,! and?are two very important and commonly used operators, respectivelyNon-empty assertionandOptional chain operation. Let’s briefly introduce the two below.
1. Non-empty assertion operator!
1.1 Meaning
Non-null assertion operator ! (Non-null assertion operator) is used to tell the TypeScript compiler.A value is definitely not null or undefined in the current situation.Even if TypeScript's type system cannot infer this. This bypasses TypeScript's type checking and directly asserts that the value is not null or undefined.
🌰
let user = { name: 'Alice', age: 25 }; // TypeScript will think that it may be undefined because it is not defined in the user object // Use a non-null assertion to tell TypeScript that I am sure that exists and can force it to be treated as a valid object.(!.length);
Here, ! tells TS that there must be a value, so it can be called safely. If it is really undefined, a runtime error will be thrown.
const singleRef = ref(); const open = () => { !.openDialog(); };
Here ! tells TS that although it may be null or undefined, it is certain that there must be a value when calling openDialog, so type checking is skipped.
1.2 Applicable scenarios
- When you are sure that a value will not be null or undefined and the TypeScript compiler cannot infer this, you can use ! to inform TS that the value must exist when it runs.
- In some cases, it may be that the external library's API or some logic in the code causes TS to fail to infer the type of a certain value, and you can use ! to force the value to be not null or undefined.
1.3 Things to note
1) Overuse! will make the TypeScript type system meaningless, which may cause errors at runtime. Because it is forced to tell TypeScript that this value will not be null or undefined, but it may actually be, this will cause a potential runtime error.
2)Use with caution, only inVery sureThe value will not be used if it is null or undefined.
2. Optional chain operator?
2.1 Meaning
Optional chaining operator (Optional chaining operator) allows us to safely access an object's properties or methods without worrying about null or undefined in the middle. If a part of the object is null or undefined, the expression short-circuits and returns undefined without throwing an error.
🌰
const user = { name: 'Alice', address: { city: 'New York' } }; // Use optional chain operator to securely access(?.city); // "New York" // Continuous chain callconst length = ?.street?.length; // undefined instead of throwing an error(length); // undefined
Here, ?.city can safely access the address property. Even if it is undefined, an error will not be thrown, but will return undefined.
const singleRef = ref(); const open = () => { ?.openDialog(); };
Here ? means that if is null or undefined, the openDialog method is not called, but returns undefined to avoid throwing an error.
2.2 Applicable scenarios
- When accessing deep nested properties of an object, you are not sure whether an intermediate property exists. Use ? Can prevent errors caused by accessing null or undefined properties.
- When a method is called or a property is accessed, the object itself or some properties may be null or undefined. The optional chain operator helps us avoid errors.
2.3 Things to note
1) The optional chain operator can prevent errors, but it will not provide a default value. If you need to return a default value, you can use it in conjunction with ?? (null value merge operator).
2) If any part of the attribute chain is null or undefined, subsequent attribute access will stop, and the result will be undefined without an exception being thrown. If this property exists, continue to access the chained property. This avoids runtime errors in the code due to accessing undefined properties, especially when dealing with data that are uncertain or dynamically structured.
3. Summary ! and ?
3.1 Different functions
- ! A non-null assertion that tells TypeScript to determine that a value is not empty, it can bypass type checking, but itself does not handle null or undefined issues.
- ? is an optional chain operator that is used to safely access object properties or methods, avoid throwing errors, and automatically handle null or undefined cases.
3.2 Use scenarios
- ! Applicable to scenarios where a value is not null or undefined is very certain. It is a forced assertion that requires developers to have clear confidence in the code.
- ? Applicable to scenarios where a certain value exists and wants to safely access nested properties or methods.
3.3 Performance considerations
- When using !, TypeScript skips type checking, but may still throw exceptions at runtime, so it does not provide runtime security.
- When using ? , TypeScript will check whether the value is null or undefined at runtime and return undefined to avoid errors.
Both operators are very useful when writing TypeScript code and can help us write more robust code.
This is the end of this article about the ! and ? operators in TypeScript. For more related TypeScript ! and ? operator content, please search for my previous articles or continue browsing the related articles below. I hope you will support me more in the future!