User-defined type guards and the is operator

When you manipulate simple JavaScript objects (also known as Plain Old JavaScript Objects, or POJOs), you can't use typeof or instanceof, as you will only match the object type. Still, sometimes you might want to perform some type checks. In those cases, you can define user-defined type guard functions with the is operator.

The following is an example:

type Dog = { 
    name: string; 
    race: string; 
}; 
 
function isDog(arg: any): arg is Dog { 
    return arg.race !== undefined; 
} 
 
console.log(isDog({name: "Pluto", race: "Saint-Hubert"})); // returns true 

As you can see here, we have defined an isDog function that returns true if the given argument has the properties we expect. Of course, the function can perform more advanced checks if needed.