'Switching on types in a factory in typescipt

Lets say I have a base class A and A1, A2, A3 all extends A. I create a factory class say, FactoryForA that implements a method say getObject as

getObject(typeToSwitch) {
  case A1: // return an  object of A1
  case A2: // return an object of A2
  case A3: // return an object of A3
}

I am looking for a way to make the argument typeToSwitch type safe.



Solution 1:[1]

What I came up with is getObject<T extends new(...args: any[]) => A>(typeToSwitch: T).

It says T is something that extends A and is constructible, so it allows us to use a type as value(I am yet to figure this why). Also getObject(T extends A) does not work(why only a constructible type is supported.)

If anyone has suggestions or explanations please update the answer or comment.

Here is a link to an example of what I said above.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nilesh Kumar