How do mapped types interact with union types when mapping over `keyof (A | B)`?
Short answer
`keyof (A | B)` produces only the INTERSECTION of keys common to both A and B (since only guaranteed-present keys are safe to access on either type), which can be a surprising and non-obvious result if you expected all keys from both types combined.
Advertisement
AModel answer
`keyof (A | B)` produces only the INTERSECTION of keys common to both A and B (since only guaranteed-present keys are safe to access on either type), which can be a surprising and non-obvious result if you expected all keys from both types combined.
interface A { x: number; y: number; }
interface B { x: number; z: number; }
type Keys = keyof (A | B); // 'x' only — the only key guaranteed on bothReal-world example
Debugging an unexpectedly narrow mapped type result, tracing it back to keyof behavior on a union rather than an intersection.
Likely follow-ups
- How does `keyof (A & B)` differ from `keyof (A | B)` in this respect?
Related topics