Home > database >  How to get object of specific type from collection of its parent?
How to get object of specific type from collection of its parent?

Time:03-03

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

CodePudding user response:

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.

CodePudding user response:

You can use instanceof, as follows:

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