Home > other >  How to type list of objects that extend an object with generic types
How to type list of objects that extend an object with generic types

Time:01-10

How to type list (object, record, map; anything with key) of objects which are extending another class with generics?

I don't really care about what kind of generics have each object. I just want to type it like "anything that extend A".

// valid abstract class
abstract class A<SOME_TYPE> {
  private something: SOME_TYPE;
  constructor(xxx: SOME_TYPE) {
    console.log(xxx);
  }
}

// valid class
class B extends A<number> {}


// I want a list of objects that extend A
const listOfObjects: Record<string, A<any>> = {
  b: B, // TS2741 error
};
// nor this
const listOfObjects: Record<string, typeof A> = {
  b: B, // Type 'typeof B' is not assignable to type 'typeof A'
};

ts v 4.4.4

CodePudding user response:

You should use construct signatures as the type.

abstract class A<SOME_TYPE> {
  private something!: SOME_TYPE;

  constructor(arg: string) {}
}

class B extends A<number> {}
class C extends A<number> {}

const listOfObjects: Record<string, new (...args: any) => A<any>> = {
  b: B,
  c: C
};

Playground

  • Related