Stwosch
Stwosch

Reputation: 642

Cannot use 'new' with the Function type in TypeScript

I have this code:

const BlockConstructors: Function[] = [
 OBlock,
 IBlock,
 TBlock
];

function randomFromArray(array: any[]) {
  return array[Math.floor( Math.random() * array.length )];
}

const BlockConstructor: Function = random(BlockConstructors);
const block: Block = new BlockConstructor();

I try to draw a some block constructor from array and then create a new object, all my block constructors in array extends Block class. I get error:

Cannot use 'new' with an expression whose type lacks a call or construct signature.

Why this error appears?

Upvotes: 4

Views: 4177

Answers (1)

Daniel Rosenwasser
Daniel Rosenwasser

Reputation: 23443

Your code isn't self-contained, but here's the boiled down reason.

Function isn't new-able. Only three things can be new'd in TypeScript:

  1. Types with construct signatures
  2. Types with no construct signatures, but with call signatures that return void
  3. any

You really want the first one.

Try switching from Function to (new () => Block).

Upvotes: 11

Related Questions