TypeScript: Cannot create an instance of an abstract class2 min read

Let A: abstract Class and B: B extends A. Now try writing a function with return type of (typeof A) and returning (typeof B)

Extending an abstract class

//Type Input
abstract class Input {
constructor() {
}
}
//Input Select
class Select extends Input {
constructor() {
super();
}
}
//Input Text
class TextField extends Input {
constructor() {
super();
}
}
//Create a new element from string name
let getInputType = (type: string): typeof Input => {
switch (type) {
case 'select':
return Select;
break;
default:
return TextField;
}
}
let elemType = getInputType('select');
//Create new elem
let elem = new elemType();

I get the following error

let elemType: new () => Input
Cannot create an instance of an abstract class.

Solution

Store the type of Input in a variable InputClass

type InputClass = typeof Input;

Extend the type with an Interface InputLike

interface InputLike extends InputClass { };

Result

//Type Input
abstract class Input {
constructor() {

}
}

type InputClass = typeof Input;
interface InputLike extends InputClass { };

//Input Select
class Select extends Input {
constructor() {
super();
}
}

//Input Text
class TextField extends Input {
constructor() {
super();
}
}

//Create a new element from string name
let getInputType = (type: string): InputLike => {
switch (type) {
case 'select':
return Select;
break;
default:
return TextField;
}
}

let elemType = getInputType('select');

//Create new elem
let elem = new elemType();