Question

Given the following code:

class Type
{
    static Property = 10;
}

class Type1 extends Type
{
    static Property = 20;
}

class Type2 extends Type
{
    static Property = 30;
}

I would like to make a function that can return an array of types that all inherit from the same base, that allows access to the "static side" of the class. For example:

function GetTypes(): typeof Type[]
{
    return [Type1, Type2];
}

So now ideally I could go:

GetTypes(0).Property; // Equal to 20

However it doesn't seem like there is syntax for storing multiple typeof types in an array.

Is this correct?

Was it helpful?

Solution

Of course there is. Your code is correct minus the return type of the GetTypes function. (To be clear Steve's answer would solve your issue as well, this is just another approach without making use of interfaces).

Change the return type of the GetTypes function to:

function GetTypes(): Array<typeof Type>
{
    return [Type1, Type2];
}

This should to the trick.

OTHER TIPS

The correct way to do this would be to create an interface that describes the properties (or operations) supported by the type (that don't belong to an instance of the type):

interface Test {
    x: number;
}

class MyType {
    static x = 10;
}

class MyOtherType {
    static x = 20;
}

var arr: Test[] = [MyType, MyOtherType];

alert(arr[0].x.toString());
alert(arr[1].x.toString());

No. It is currently only supported for single identifiers. I have made a feature request here: https://typescript.codeplex.com/workitem/1481

Nonetheless you can simply create a dummy interface to capture typeof Type and then use it in an Array i.e:

class Type
{
    static Property = 10;
}

class Type1 extends Type
{
    static Property = 20;
}

class Type2 extends Type
{
    static Property = 30;
}

// Create a dummy interface to capture type
interface IType extends Type{}

// Use the dummy interface
function GetTypes(): IType[]
{
    return [Type1, Type2];
}

GetTypes[0].Property; // Equal to 20

See it on the playground

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top