Search code examples
javascriptarraystypescriptinstanceoftypeof

Check if array contains an instance of a particular class in TypeScript


I come from .net background and new to typescript. I have an array that contains objects from different classes that implement a common interface. I would like to check if the array contains an object from a particular class. I tried using a combination of 'includes' and 'instanceof' but didn't succeed. Thanks in advance.

Suppose classes 'C1', 'C2' & 'C3' implement the interface 'Int1'. Array 'array01' can hold the objects of classes that implement interface 'Int1'.

private static array01: Int1[] = [];

if(array01.includes(instanceof C1)) ??? //Want to check if 'array01' contains an object of class 'C1'.

Solution

  • Try

    private static array01: Int1[] = [];
    
    if(array01.find(arr => arr instanceof C1)) {}
    

    For array filter

    private static array01: Int1[] = [];
    
    if(array01.filter(arr => arr instanceof C1).length) {}