Optional vs undefined Union
You'll learn the crucial difference between marking a property as optional (?) versus explicitly making it a union with undefined.
The Core Difference
When you write { x?: number }, you're saying "the property x might not be present at all." But when you write { x: number | undefined }, you're saying "the property x must be present, but its value can be undefined."
Think of it like a form: optional means the field might be left completely blank (not even on the form), while | undefined means the field must exist on the form, but you're allowed to write "N/A" in it.
Presence vs Value
type Optional = {
x?: number;
};
type UndefinedUnion = {
x: number | undefined;
};
const obj1: Optional = {}; // ✓ Valid - property absent
const obj2: UndefinedUnion = {}; // ✗ Error! Property 'x' is missing
const obj3: UndefinedUnion = { x: undefined }; // ✓ Valid - property present with undefined
const obj4: Optional = { x: undefined }; // ✓ Also valid!
Checking the Difference
With optional properties, you can check for presence using the in operator:
type Config = {
timeout?: number;
};
const config: Config = {};
if ('timeout' in config) {
// This block won't run - property doesn't exist
}
With undefined unions, the property always exists:
type Settings = {
timeout: number | undefined;
};
const settings: Settings = { timeout: undefined };
if ('timeout' in settings) {
// This block WILL run - property exists (even though it's undefined)
}
Key Takeaway: Use ? when a property may be absent entirely; use | undefined when the property must always be present but can have an undefined value. Optional properties can also be set to undefined, but they don't require the key to exist at all.