typescripttypescript2.0

What is reason to use is operator in TypeScript?


What is reason to use is operator in TypeScript in this case?

type Species = "cat" | "dog";


interface Pet {
   species: Species
}

interface Cat extends Pet {

}

function petIsCat(pet: Pet): pet is Cat {
   return pet.species === "cat";
}

Why to use pet is Cat instead boolean if body returns bool type?


Solution

  • boolean is just a data type while 'is' operator is used for type-testing. Let me change your example a little bit:

    type Species = 'cat' | 'dog';
    
    interface Pet {
        species: Species;
    }
    
    class Cat implements Pet {
        public species: Species = 'cat';
        public meow(): void {
            console.log('Meow');
        }
    }
    
    function petIsCat(pet: Pet): pet is Cat {
        return pet.species === 'cat';
    }
    
    function petIsCatBoolean(pet: Pet): boolean {
        return pet.species === 'cat';
    }
    
    const p: Pet = new Cat();
    
    p.meow(); // ERROR: Property 'meow' does not exist on type 'Pet'.
    
    if (petIsCat(p)) {
        p.meow(); // now compiler knows for sure that the variable is of type Cat and it has meow method
    }
    
    if (petIsCatBoolean(p)) {
        p.meow(); // ERROR: Property 'meow' does not exist on type 'Pet'.
    }
    

    Of course you can use type casting:

    (<Cat>p).meow(); // no error
    (p as Cat).meow(); // no error
    

    But it depends on the scenario.


    Docs: