Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use 'new' with the Function type in TypeScript

Tags:

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?

like image 580
Stwosch Avatar asked Sep 07 '25 00:09

Stwosch


1 Answers

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).

like image 128
Daniel Rosenwasser Avatar answered Sep 11 '25 03:09

Daniel Rosenwasser