Categories
Programming

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();

Categories
Programming

Why I use Typescript + babel?46 sec read

  • Types helps me to avoid silly mistakes by forcing me to stick to a common rule rather than total chaos.
  • Strip the types and you get javascript, so you don’t loose touch with it
  • I use a javascript transpiler (Babel) anyway. So why not exploit types.
  • It works very well with VS-Code which is an awesome product.

Typescript vsĀ Flow

  • Nothing wrong with, but its harder to set up and documentation is not that good.
  • In case of Typescript just use VS-Code which I use anyway
  • It is pretty much the same. So everything comes down to convenience.

Typescript vs Babel

  • Babel wins for me because of plugins and presets.

Purescript?

  • Well I tried, but the documentation isn’t good enough
  • Laaaaaaaazyyyyy…