Null-checking is a crucial aspect of TypeScript that helps developers write more robust and error-free code. It involves verifying whether a value is null or undefined before using it, preventing runtime errors and improving overall code quality.
TypeScript's strict null checks, enabled by the --strictNullChecks
compiler option, enforce explicit handling of null and undefined values. This feature helps catch potential errors early in the development process.
let name: string;
name = null; // Error: Type 'null' is not assignable to type 'string'
let age: number | null;
age = null; // OK: null is allowed in union type
TypeScript 3.7 introduced optional chaining, a feature that simplifies null-checking when accessing nested properties or calling methods on potentially null objects.
interface User {
name: string;
address?: {
street: string;
city: string;
};
}
function getCity(user: User): string | undefined {
return user.address?.city;
}
In this example, user.address?.city
returns undefined
if address
is null or undefined, preventing a runtime error.
The nullish coalescing operator (??
) provides a concise way to handle default values for null or undefined expressions.
function greet(name: string | null | undefined): string {
return `Hello, ${name ?? "Guest"}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!
console.log(greet(null)); // Output: Hello, Guest!
null
or undefined
when a value can be nullable.While type assertions can be used for null-checking, they should be used sparingly and with caution. Refer to Type Assertion Best Practices for more information.
Effective null-checking is essential for writing reliable TypeScript code. By leveraging strict null checks, optional chaining, and other TypeScript features, developers can significantly reduce null-related errors and improve code quality.
For more advanced type handling, explore TypeScript Utility Types and Conditional Types to create even more robust type-safe code.