DEV Community

Discussion on: Why does typescript not conditionally pick the right type in a union?

Collapse
 
stojakovic99 profile image
Nikola Stojaković • Edited

This is completely normal - you have come into territory where TypeScript is trying to protect you from accessing potentially non-existing property.

If you take a look at documentation for union types you will find this:

If we have a value that has a union type, we can only access members that are common to all types in the union.

You need to refactor your solution to handle this case in a better way. Btw, why you don't use intersection types?

Collapse
 
hnicolas profile image
Nicolas Hervé

You should look at type guards : typescriptlang.org/docs/handbook/a...