Default Values with Optional Properties
What you'll learn: How to use destructuring with default values to provide fallback data when working with optional object properties.
The Core Idea
When you have an object with optional properties, you can't always be sure those properties will exist. JavaScript destructuring allows you to specify default values that kick in when a property is missing or undefined. TypeScript combines this JavaScript feature with optional property types to give you both type safety and convenient fallback behavior.
Think of it like ordering a customizable meal: if the customer doesn't specify whether they want sauce, you automatically give them the house sauce. The sauce property is optional in the order, but you always end up with some sauce value to work with.
Destructuring with Defaults
When you destructure an object parameter, you can provide defaults right in the parameter list:
type UserSettings = {
theme?: string;
notifications?: boolean;
};
function applySettings({ theme = 'light', notifications = true }: UserSettings) {
console.log(`Theme: ${theme}, Notifications: ${notifications}`);
}
applySettings({}); // Uses both defaults
applySettings({ theme: 'dark' }); // Uses default for notifications
applySettings({ theme: 'dark', notifications: false }); // No defaults
The ? in the type says "this property might not exist," while the = in the destructuring says "if it doesn't exist (or is undefined), use this value instead."
Why This Pattern Matters
This combination eliminates the need for manual checking or fallback logic inside your function body. You get clean, declarative code where the defaults are visible right in the function signature.
Key Takeaway: Combine optional properties (?) in types with destructuring defaults (=) in parameters to handle missing values elegantly without extra runtime checks.