Can anyone assist me in creating a function that retrieves all instances of a specified type from a list of candidates, each of which is derived from a shared parent class?
For example, I attempted the following code:
class A {
protected children: A[] = [];
getChildrenOfType<T extends A>(): T[] {
let result: T[] = [];
for (let child of this.children) {
if (child instanceof T)
result.push(<T>child);
}
return result;
}
}
using classes like:
class B: extends A {}
class C: extends B {}
class D: extends A {}
However, the code does not compile. The error message "'T' only refers to a type but is being used as a value here" appears when using child instanceof T
. This issue seems to be related to the generic type. What is the correct approach to solve this problem? Do I need additional steps to filter objects based on generic types?