'How to get object of specific type from collection of its parent?

abstract class A {
}

export class B extends A{
}

export class C extends A{
}
....
getFirstC(aListe:A[]): C {
//get the first c object in alist
}

How to get the first element of type C from a list of type A?

We want to loop through a list of parent type(A) and find a way to identify the concrete type of each element.

According to documentation there is an example using typeof, but it is not yet clear how to use it:

type P = ReturnType<typeof f>;
    
type P = {
    x: number;
    y: number;
} 

Thank you in advance



Solution 1:[1]

That's not possible to achieve.

The parent class doesn't have any info what are the child classes inherited from that parent class

That means, if you are getting aListe:A[] i.e each element of Array is an object of A class, then this object can't access the properties or functions of the child classes B or C.

However, that's not true in the opposite case. If you have something like aListe:B[], then all these objects will have access to properties of A class.

Solution 2:[2]

You can use instanceof, as follows:

function getFirstC(aList: A[]): C {
  return aList.find(object => object instanceof C)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Himanshu
Solution 2 www.admiraalit.nl