Optional vs undefined Union Types
You'll learn: The subtle but important difference between marking a parameter as optional with ? versus explicitly typing it as T | undefined.
The Core Difference
When you write param?: string, you're saying "this parameter can be omitted entirely." When you write param: string | undefined, you're saying "this parameter must be provided, but its value can be undefined."
Optional with ?
function greet(name?: string) {
console.log(name);
}
greet(); // ✅ Valid - omitted
greet(undefined); // ✅ Valid - explicitly undefined
greet("Alice"); // ✅ Valid
Union with undefined
function greet(name: string | undefined) {
console.log(name);
}
greet(); // ❌ Error - argument required!
greet(undefined); // ✅ Valid - explicitly passed
greet("Alice"); // ✅ Valid
When Each Matters
The difference becomes important when calling functions. With ?, callers can skip the argument entirely. With | undefined, they must pass something, even if it's undefined.
Think of optional parameters like a restaurant menu item marked "optional sides" — you can skip it. A | undefined parameter is like a required form field that accepts "prefer not to answer" — you must interact with it, even if just to say "none."
Practical Impact
function setWidth(width?: number) {
// Can be called with no arguments
}
function setHeight(height: number | undefined) {
// Must explicitly pass undefined if no value
}
setWidth(); // ✅ Fine
setHeight(); // ❌ Error
setHeight(undefined); // ✅ Must be explicit
Key Takeaway: Use param?: when the argument is truly optional. Use param: T | undefined when you want to force callers to explicitly acknowledge they're passing no value.