TypeScript · Senior · Question 36 of 75

Why can't you write a.x for a: { x: string } | { y: number }?

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.

Further reading

Problem with a question

TypeScript · Senior · question 36

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz