Type Guards and Differentiating Types

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();
}
doc_TypeScript
2016-10-04 19:25:39
Comments
Leave a Comment

Please login to continue.