o7planning

TypeScript instanceof operator

View more Tutorials:

Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- instanceof operator

The instanceof operator is used to check if an object is an object of a specified class. This operator returns true or false.
Syntax:


anObject instanceof AClass;

let result = anObject instanceof AClass;
The characteristics of the instanceof operator:
  • The left side of the instanceof expression cannot be a primitive data type. It must be an object.
  • The right side of the instanceof expression must be a class.
We will clarify the above characteristics of the instanceof operator through examples:
The following example shows that the compiler will report an error if the left side of the instanceof expression is a primitive value.
  • null, string, number, boolean, NaN, undefined, Symbol
instanceof_ex1a.ts

class Abc { }

let aNaN = NaN;
aNaN instanceof Abc; // Compile Error!!!

let aNumber = 123;
aNumber instanceof Abc; // Compile Error!!!

let anUndefined = undefined;
anUndefined instanceof Abc; // Compile Error!!!

let aSymbol = Symbol("Something");
aSymbol instanceof Abc; // Compile Error!!!

let aNull = null;
aNull instanceof Abc; // Compile Error!!!

let aBoolean = true;
aBoolean instanceof Abc; // Compile Error!!!

let aBooleanObject = new Boolean(true); // Boolean Object
aBooleanObject instanceof Abc; // Compile OK!
Example: The left side of the instanceof expression must be an object:
instanceof_ex1b.ts

interface IEmployee {
    empId: number,
    empName: string
}
class Mouse {}
class Cat {}

var anObject1 = {name: 'Tom', gender: 'Male'};
anObject1 instanceof Mouse; // Compile OK!

var anObject2:IEmployee = {empId: 1, empName: 'Donald'};
anObject2 instanceof Cat; // Compile OK!

var anObject3 = new Mouse();
anObject3 instanceof Cat; // Compile OK!
Example: The compiler will report an error if the right side of the instanceof expression is not a class.
instanceof_ex2a.ts

interface IStaff {
    staffId: number,
    staffName: string
}
class Person {}

let aAnyObject = {}; // Any Objet

aAnyObject instanceof IStaff; // Compile Error !!!!  (IStaff is not a class).

aAnyObject instanceof Person; // Compile OK!

2- Examples

In this example, we have Animal, Duck and Horse classes, and IMove interface. Let's create a few objects and see how the instanceof operator works.
instanceof_ex3.ts

interface IMove {
    move(): void;
}
class Animal implements IMove {
    move() {
        console.log("Animal move!");
    }
}
class Duck extends Animal {}
class Horse extends Animal {}

let donald = new Duck();
console.log("donald instancef Duck? " + (donald instanceof Duck)); // true
console.log("donald instancef Animal? " + (donald instanceof Animal)); // true
console.log("donald instancef Horse? " + (donald instanceof Horse)); // false

let daisy: IMove = new Duck();
console.log("daisy instancef Duck? " + (daisy instanceof Duck)); // true
console.log("daisy instancef Animal? " + (daisy instanceof Animal)); // true
console.log("daisy instancef Horse? " + (daisy instanceof Horse)); // false

let iMove: IMove = {
     move : function() {
         console.log('IMove move!');
     }
};
console.log("iMove instancef Duck? " + (iMove instanceof Duck)); // false
console.log("iMove instancef Animal? " + (iMove instanceof Animal)); // false
console.log("iMove instancef Horse? " + (iMove instanceof Horse)); // false
Output:

donald instancef Duck? true
donald instancef Animal? true
donald instancef Horse? false
daisy instancef Duck? true
daisy instancef Animal? true
daisy instancef Horse? false
iMove instancef Duck? false
iMove instancef Animal? false
iMove instancef Horse? false
Example: Use the instanceof operator to distinguish the parameter type passed to the function.
instanceof_cls_ex1.ts

class Food {
   foodName: string;
   constructor(foodName: string) {
       this.foodName = foodName;
   }
}
class Drink {
    drinkName: string;
    constructor(drinkName: string) {
        this.drinkName = drinkName;
    }
}
function getName(arg: Food | Drink) {
    if(arg instanceof Food)  {
        let food = arg as Food;
        return food.foodName;
    } else {
        let drink = arg as Drink;
        return drink.drinkName;
    }
}  
let coca = new Drink("Cocacola");
console.log(getName(coca)); // Cocacola

let pho = new Food("Vietnamese Pho");
console.log(getName(pho)); // Vietnamese Pho
Output:

Cocacola
Vietnamese Pho
Duck Typing
The instanceof operator is used to check if an object is an object of a class. It cannot be used for interfaces, and you need another technique, see example:
duck_typing_ex1.ts

interface IWorker {
    workerId: number,
    workerName: string
}
interface IStudent {
    studentId: number,
    studentName: string
}
function getNameOf(arg: IWorker | IStudent) {
    let test1 = arg as IWorker;
    if(test1.workerId && test1.workerName) {
         return test1.workerName;
    }
    let test2 = arg as IStudent;
    return test2.studentName;
}  
let tom = {workerId: 1, workerName: 'Tom'};
let jerry = {studentId: 1, studentName: 'Jerry'};

console.log(getNameOf(tom)); // Tom
console.log(getNameOf(jerry)); // Jerry
Output:

Tom
Jerry

3- typeof operator

View more Tutorials: