Union types in TypeScript allow developers to define a variable that can hold multiple types of values. When working with union types, it’s common to encounter the need to include `null` and `undefined` as possible values. Understanding how to effectively use union types with `null` and `undefined` is crucial for writing robust and type-safe applications. Below, we will explore the concept, provide practical examples, discuss best practices, and highlight common mistakes.
A union type is defined using the pipe (`|`) operator. For instance, if you want a variable to accept either a string or a number, you can define it as follows:
let value: string | number;
When including `null` and `undefined`, you can extend the union type:
let value: string | number | null | undefined;
Consider a function that processes user input. You might want to allow the input to be a string, or it could be `null` or `undefined` if the user has not provided any value:
function processInput(input: string | null | undefined) {
if (input === null) {
console.log("Input is null");
} else if (input === undefined) {
console.log("Input is undefined");
} else {
console.log("Processing input: " + input);
}
}
In this example, the function checks the type of the input and handles each case appropriately. This ensures that the function behaves correctly regardless of the input type.
Here’s how optional chaining can simplify code when dealing with potentially `null` or `undefined` values:
interface User {
name: string;
age?: number | null;
}
function getUserAge(user: User | null): string {
return `User age is: ${user?.age ?? 'not provided'}`;
}
By following these guidelines, developers can effectively manage union types with `null` and `undefined`, leading to cleaner, safer, and more maintainable code.