gotchatypescriptnoneModerate
exactOptionalPropertyTypes Distinguishes Missing vs Undefined
Viewed 0 times
TypeScript 4.4+
exactOptionalPropertyTypesoptional propertyundefinedmissing vs undefinedstrict
Error Messages
Problem
With standard optional properties, setting a field to 'undefined' and omitting it entirely are treated identically. This masks bugs where code explicitly sets a field to undefined when it should omit it.
Solution
Enable 'exactOptionalPropertyTypes: true' to make optional fields only accept their declared type, not undefined.
// tsconfig.json
{ "compilerOptions": { "exactOptionalPropertyTypes": true } }
interface User {
name: string;
nickname?: string; // can be omitted, but NOT set to undefined
}
const u1: User = { name: 'Alice' }; // OK — omitted
const u2: User = { name: 'Alice', nickname: 'Al' }; // OK
const u3: User = { name: 'Alice', nickname: undefined }; // Error!
// Type 'undefined' is not assignable to type 'string'
// To explicitly allow undefined, add it to the type:
interface User2 {
name: string;
nickname?: string | undefined;
}Why
Optional property '?' means the key can be absent from the object. Setting a key to 'undefined' is semantically different — the key exists with an undefined value. These have different behavior in JSON.stringify, 'in' checks, and Object.keys.
Gotchas
- Not included in 'strict: true' — must enable separately.
- Many popular libraries violate this contract; you may need to adjust when using their types.
- Partial<T> sets fields to 'T | undefined' which violates exactOptionalPropertyTypes — use a custom Partial variant.
Revisions (0)
No revisions yet.