Search code examples
angulartypescriptundefined

check the type of an Angular object that can be undefined as well


I am learning Angular and I would like to write a method that returns true if the type of the object is Dog (it has a woof property).

This is what I have so far:

export class SomeClass {
   public animal?: Dog | Cat;
   ...
   public isDog() {
    return 'woof' in this.animal;  <-- Object is possibly 'undefined'
  }
}

Then I show the content based on the type of the object this way:

<div *ngIf="isDog(); then dogCardTemplate else catCardTemplate"></div>

My problem is that this.animal can be undefined and the following error appears:

Object is possibly 'undefined'.

Could you please help me to solve this in a simple way with as less code line as possible?


Solution

  • The proper way to check if is the following:

    export class SomeClass {
       public animal?: Dog | Cat;
       
       public isDog() {
          return  this.animal // check to see if its defined first
               && 'woof' in this.animal; // animal type check later
       }
    
    }
    

    Why?

    Well since the property is optional, we need to make a check to see if it is defined and only after that can we make a check for if its a dog.

    Note: if you want to check that it is a cat, you will need to repeat the undefined check.