exactOptionalPropertyTypes: Optional vs Undefined
What you'll learn: How exactOptionalPropertyTypes changes the way TypeScript treats optional properties, making them truly optional instead of implicitly allowing undefined.
The Problem with Optional Properties by Default
Without exactOptionalPropertyTypes, TypeScript treats these two type definitions as identical:
interface Person {
name: string;
age?: number;
}
interface PersonExplicit {
name: string;
age: number | undefined;
}
Both allow you to:
- Omit the
ageproperty entirely - Set
agetoundefinedexplicitly
This conflation can hide bugs. When a property is optional, it should mean "you can leave it out." When it's undefined, it should mean "you must provide it, but the value can be undefined." These are conceptually different!
What exactOptionalPropertyTypes Does
When you enable exactOptionalPropertyTypes in your tsconfig.json, TypeScript makes a crucial distinction:
- Optional properties (
age?: number) mean "the key may be absent" - Union with undefined (
age: number | undefined) means "the key must be present, but can beundefined"
Think of it like a form: An optional field is one you can skip entirely. A field that accepts undefined is one you must touch, even if you write "N/A."
Practical Impact
With exactOptionalPropertyTypes enabled:
interface Config {
timeout?: number;
}
const validConfig: Config = {}; // ✓ OK - property omitted
const invalidConfig: Config = { timeout: undefined }; // ✗ Error!
If you actually want to allow explicit undefined, you must declare it:
interface ConfigExplicit {
timeout?: number | undefined;
}
const nowValid: ConfigExplicit = { timeout: undefined }; // ✓ OK
Why This Matters
This flag prevents a common mistake: accidentally passing undefined when you should be omitting the property entirely. It makes your API contracts more precise and catches cases where undefined values slip through when they shouldn't.
Key Takeaway: exactOptionalPropertyTypes enforces the semantic difference between "property can be absent" and "property can be undefined," leading to more precise type checking and fewer runtime surprises.