Type Guards and Differentiating Types
Union types are useful for modeling situations when values can overlap in the types they can take on. What happens when we need to know specifically whether we have a Fish
? A common idiom in JavaScript to differentiate between two possible values is to check for the presence of a member. As we mentioned, you can only access members that are guaranteed to be in all the constituents of a union type.
let pet = getSmallPet(); // Each of these property accesses will cause an error if (pet.swim) { pet.swim(); } else if (pet.fly) { pet.fly(); }
To get the same code working, we’ll need to use a type assertion:
let pet = getSmallPet(); if ((<Fish>pet).swim) { (<Fish>pet).swim(); } else { (<Bird>pet).fly(); }
Please login to continue.