mardi 11 octobre 2016

Typescript - type to represent any class?

What type should I use in typescript to represent any class?

I'm trying to write a function that takes an array of classes and returns an array with different order.

function shuffle(classes: typeof Object[]) : typeof Object[] {
    return ...;
}

class A { }
class B extends A { }
class C extends B { }
class D extends B { }
suffle([A, B, C, D]);

Argument of type 'typeof A[]' is not assignable to parameter of type 'ObjectConstructor[]'.

Then I've tried:

suffle([typeof A, typeof B, typeof C, typeof D]);

error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'ObjectConstructor[]'. Type 'string' is not assignable to type 'ObjectConstructor'.

What's the right way? Generics? How? This doesn't work:

export function <T extends typeof Object> shuffle(classes: T[]) : T[]

This neither:

export function <T extends Object> sortClassesBySpeciality(classes: typeof T[]) : typeof T[]

(The ultimate goal is to sort the classes by level of extends from Object.)





Aucun commentaire:

Enregistrer un commentaire