BBaysinger
BBaysinger

Reputation: 6987

Typing as Class in TypeScript

I have an interface or abstract class in TypeScript, and I have a whole bunch of classes that either implement/extend the interface/class, and I want to make an array out of all the subclasses' constructors, but I want the array typed as the interface/superclass. Is this possible?

So if I have:

export interface Section {
    somePropName: string;
}

or:

export class AbstractSection {
    somePropName: string;
}

And then I have:

arrayOfClasses: any[] = [
    SectionSubclass1,
    SectionSubclass2,
    SectionSubclass3,
    SectionSubclass4,
    SectionSubclass5,
];

Can I type arrayOfClasses to anything other than any[]? I'd like to get as specific as possible. I know in ActionScript you could at least do Vector.<Class>, and in Haxe you could do Array<Class>, but in TypeScript you can't even type as Class, AFAIK.

Upvotes: 2

Views: 186

Answers (1)

Behrooz
Behrooz

Reputation: 2371

If you want to store classes:

arrayOfClasses: Array<typeof AbstractSection> = [...];

If you want to store instances of the classes or implementation of interfaces:

arrayOfClasses: AbstractSection[] = [...];

Upvotes: 3

Related Questions