Advertisement
Advanced TypeScript, Nullability: strictNullChecks, Optional Chaining & Nullish Coalescing

How do you correctly type an object property that's genuinely optional in one sense but should never be explicitly set to 'undefined', using 'exactOptionalPropertyTypes'?

Short answer

By default, `prop?: string` allows BOTH omitting the property entirely AND explicitly assigning it the value 'undefined' — these are usually treated as equivalent.

Save TypeScript mock interview
Advertisement
AModel answer
By default, `prop?: string` allows BOTH omitting the property entirely AND explicitly assigning it the value 'undefined' — these are usually treated as equivalent. Enabling exactOptionalPropertyTypes distinguishes them: explicitly setting a property to undefined becomes a type error unless 'undefined' is also included in its declared type, catching a subtle but meaningful difference some APIs (like some ORMs) actually care about.
// tsconfig.json: { "exactOptionalPropertyTypes": true }
interface Config {
  timeout?: number;
}
const c: Config = { timeout: undefined }; // Error with exactOptionalPropertyTypes: true
const c2: Config = {}; // OK -- omitting entirely is fine
Real-world example
Catching a subtle bug in an ORM or API client where explicitly setting a field to undefined has different runtime semantics than omitting it entirely.
Likely follow-ups
  • Why might some libraries genuinely distinguish between 'omitted' and 'explicitly undefined' at runtime?
Related topics