Let's consider a type predicate similar to the one shown in the TypeScript documentation:
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
Now, imagine we have some code structured like this:
function inRightPlace(pet: Fish | Bird) {
return (
(isFish(pet) && pet.inWater()) ||
(!isFish(pet) && pet.inSky())
);
We want to optimize this by avoiding calling isFish
function twice. Our attempt looks like this:
function inRightPlace(pet: Fish | Bird) {
const isAFish = isFish(pet);
return (
(isAFish && pet.inWater()) ||
(!isAFish && pet.inSky())
);
However, the TypeScript compiler raises an issue because the check on isAFish
doesn't act as a recognized type test for pet
. Various attempts have been made to assign a type to isAFish
, but it seems that type predicates cannot be used in this way.
It appears there may not be a way to avoid the duplicate call to the type guard function in this scenario. Further research online has yielded limited information, so confirmation from experts would be greatly appreciated.