Typescript method with type as parameter

Given this hierarhcy class

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 that takes an array of classes (not an instance), extends A and calls m() for each element of the array:

 function looper(classes: A[]) { classes.forEach(c => cm()); } 

This expects an array of instances of A or its subclasses.

How can I get a method that takes as classes of arguments that extend A?

Generics as directed by @Oscar Paz

EDIT 1

In addition, the input to the looper must be stored in the property of the object:

 export class Container { public klazzes: A[]; } 

I

+5
source share
3 answers

Well, using generics:

 function callM<T extends typeof A>(arr: T[]): void { arr.forEach(t => tm()); } 

Now you can do:

 callM([A, B, C]); // OK callM([A, B, string]); // Error 

If you want to keep the values:

 class Container { public klazzes: (typeof A)[]; } const cont: Container = new Container(); callM(cont.klazzes); 
+1
source

Not sure if this is what you were looking for - besides what @Oscar suggested, you can create a generic class to store the array in a property of type T[] , as shown below.

 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'}; } export class Container<T extends typeof A> { public klazzes: T[]; constructor() { this.klazzes = []; } public callM<T extends typeof A>(arr: T[]): void { arr.forEach(t => console.log(tm()) ); } } // usage let cont = new Container(); cont.klazzes = [A, B, C]; cont.callM(cont.klazzes); 

Here is a working link

Working demo

0
source
 export class Container<T extends typeof A> { public klazzes: T[]; } 

enter image description here

does not match

 export class Container<T extends typeof A> { public klazzes: A[]; } 

Entering an array as a specific type “A” undermines the purpose of generics. therefore, I think you would like to use a pattern like 'T'

enter image description here

0
source

Source: https://habr.com/ru/post/1276269/


All Articles