Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 584
OPV Avatar asked Jul 01 '18 15:07

OPV


People also ask

What is the purpose of the operator in TypeScript?

An Operator is a symbol which operates on a value or data. It represents a specific action on working with data. The data on which operators operates is called operand.

Is type a keyword in TypeScript?

Type keyword in typescript: In typescript the type keyword defines an alias to a type. We can also use the type keyword to define user defined types.

What is ?: In TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

Is it okay to use any in TypeScript?

any. ❌ Don't use any as a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable.


1 Answers

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 is know 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.

like image 80
Dmytro Serhatyi Avatar answered Oct 28 '22 16:10

Dmytro Serhatyi