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?
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.
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 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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With