Optional Props and Default Values
You'll learn how to mark props as optional in TypeScript and provide type-safe fallback values when they're not passed.
The Core Idea
In TypeScript, you make a prop optional by adding a ? after its name in the interface. This tells TypeScript "this prop might be undefined" and allows components to be called without it. You can then provide default values safely, knowing TypeScript understands the prop might be missing.
Think of it like a restaurant menu with optional extras: the burger comes standard, but cheese is optional. If the customer doesn't order cheese, you have a default behavior (no cheese), but you won't throw an error.
Making Props Optional
interface ButtonProps {
label: string; // Required
variant?: 'primary' | 'secondary'; // Optional
disabled?: boolean; // Optional
}
function Button({ label, variant = 'primary', disabled = false }: ButtonProps) {
return (
<button className={variant} disabled={disabled}>
{label}
</button>
);
}
// All valid:
<Button label="Click me" />
<Button label="Submit" variant="secondary" />
<Button label="Go" disabled={true} />
TypeScript's Safety Guarantee
Without the ?, TypeScript would error if you called <Button label="Click" /> because it expects all props. With the ?, TypeScript knows variant and disabled are optional and won't complain when they're omitted. The default values in the destructuring assignment provide the fallback logic.
This pattern is safer than JavaScript alone because TypeScript ensures you handle the undefined case—either with defaults or explicit conditional logic.
Key Takeaway: Use the ? operator to mark props optional in your interface, and provide default values in the function parameters for clean, type-safe component APIs that don't require every prop at every call site.