Given this class hierarhcy
export class A {
static m() { return 'a'};
}
export class B extends A {
static m() { return 'b'};
}
export class C extends A {
static m() { return 'c'};
}
I need a method taking an array of classes (not instance) extending A
and calls m()
on each element of the array:
function looper(classes: A[]) {
classes.forEach(c => c.m());
}
This expects an array of instances of A or its subclasses.
How can I have a method that takes as argument classes that extend A?
Generics as pointed out by @Oscar Paz
EDIT 1
Moreover the input to looper needs to be stored in a property of an object:
export class Container {
public klazzes: A[];
}
To type a function as a parameter, type the function's parameter list and its return value, e.g. doMath: (a: number, b: number) => number . If the function's definition becomes too busy, extract the function type into a type alias.
The syntax (a: string) => void means “a function with one parameter, named a , of type string, that doesn't have a return value”. Just like with function declarations, if a parameter type isn't specified, it's implicitly any .
Well, using generics:
function callM<T extends typeof A>(arr: T[]): void {
arr.forEach(t => t.m());
}
Now you can do:
callM([A, B, C]); // OK
callM([A, B, string]); // Error
If you want to store the values:
class Container {
public klazzes: (typeof A)[];
}
const cont: Container = new Container();
callM(cont.klazzes);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With