Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript method with type as parameter

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[];
}
like image 734
Cec Avatar asked Apr 05 '18 13:04

Cec


People also ask

Can you pass a type as a parameter TypeScript?

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.

What does () => void mean TypeScript?

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 .


1 Answers

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);
like image 120
Oscar Paz Avatar answered Oct 12 '22 02:10

Oscar Paz