What is reason to use is operator in TypeScript?

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:

  • https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
  • https://basarat.gitbook.io/typescript/type-system/typeguard#user-defined-type-guards

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)