How does structural typing's handling of optional properties create potential unsoundness when assigning a type with FEWER properties to one expecting an optional property?
Short answer
Because an optional property `prop?: T` is really `prop?: T | undefined` from the type checker's perspective, a type that OMITS that property entirely (never declares it at all) is structurally compatible with one that has it as optional — this is generally safe, but combined…
Advertisement
AModel answer
Because an optional property `prop?: T` is really `prop?: T | undefined` from the type checker's perspective, a type that OMITS that property entirely (never declares it at all) is structurally compatible with one that has it as optional — this is generally safe, but combined with excess property checking being SKIPPED for non-literal assignments, it can occasionally let genuinely mismatched shapes through variables rather than literals.
interface Options { timeout?: number; }
interface Empty {}
const e: Empty = {};
const opts: Options = e; // OK -- Empty structurally satisfies Options, since 'timeout' is optionalReal-world example
Understanding why a completely unrelated, minimal object type can still satisfy an interface consisting entirely of optional properties.
Likely follow-ups
- Would this same assignment succeed if 'timeout' were a REQUIRED property instead of optional?
Related topics