TypeScript · Senior · Question 36 of 75
Why can't you write a.x for a: { x: string } | { y: number }?
- ✓Correct answer: Only common union properties are accessible; narrow the type via
'x' in a - 2Properties of union types are always read-only
- 3You have to cast
atoanyfirst - that's by design
Explanation
The compiler doesn't know which member a is, and the second has no x. After if ('x' in a) the type is narrowed. Alternatives are a common discriminant (kind) or an explicit x?: undefined in the second member.