I need a function that returns me all instances of a given type from a list of candidates, all derived from a common super class.
For instance I could write:
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;
}
}
with eg
class B: extends A {}
class C: extends B {}
class D: extends A {}
etc.
However, that doesn't compile. child instanceof T
gives me "'T' only refers to a type but is being used as a value here". However, any concrete class (eg C) works there. It's obviously the generic type that causes problems. What is the correct construct to be used for that case? Is there something else required to implement such generic filtering?
You can use this code.
class A {
protected children: A[] = [];
getChildrenOfType<T extends A>(t: new (...args: any[]) => T): T[] {
let result: T[] = [];
for (let child of this.children) {
if (child instanceof t)
result.push(<T>child);
}
return result;
}
}
The right side of the instanceof
needs to be a constructor function, eg new() => MyClass
. You can give that as a parameter to the method.
The getChildrenOfType
method can be used like this:
var a = new A();
// push some childs to a.children
a.getChildrenOfType(B)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.