David
David

Reputation: 16067

TypeScript array of types

I have the following interface:

export interface FooInterface {
    barAction(x: any) : void;
}

Then I'm implementing it:

class FooImplA implements FooInterface {
    barAction(x: any) : void {};
}

class FooImplB implements FooInterface {
    barAction(x: any) : void {};
}

class FooImplB implements FooInterface {
    barAction(x: any) : void {};
}

Now I want an array of the types FooImplA and FooImplB (not the instances).

Obviously, this works:

  let typeArray = [FooImplA, FooImplB];

But I want it strongly typed. The below is what I have in mind, which doesn't work:

  let typeArray: Array< (typeof FooInterface) > = [FooImplA, FooImplB];

Upvotes: 4

Views: 296

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164437

Using your code:

interface FooInterface {
    barAction(x: any) : void;
}

class FooImplA implements FooInterface {
    barAction(x: any) : void {};
}

class FooImplB implements FooInterface {
    barAction(x: any) : void {};
}

let typeArray = [FooImplA, FooImplB];

The type of the typeArray variable is: typeof FooImplA[], you can see that in playground by hovering your mouse over typeArray.
The reason is that the compiler infers the type of the array itself without needing to explicitly tell it that.

If you do want to have it in the code, then you can do something like:

type FooImplConstructor = { new (): FooInterface };

let typeArray: FooImplConstructor[] = [FooImplA, FooImplB];
// or
let typeArray = [FooImplA, FooImplB] as FooImplConstructor[];

Upvotes: 1

Related Questions