TS - Only a void function can be called with the 'new' keyword

Alexander Mills picture Alexander Mills · Apr 19, 2017 · Viewed 19.6k times · Source

I am getting this weird error from TypeScript:

"Only a void function can be called with the 'new' keyword."

What?

enter image description here

The constructor function, just looks like:

function Suman(obj: ISumanInputs): void {

  const projectRoot = _suman.projectRoot;

  // via options
  this.fileName = obj.fileName;
  this.slicedFileName = obj.fileName.slice(projectRoot.length);
  this.networkLog = obj.networkLog;
  this.outputPath = obj.outputPath;
  this.timestamp = obj.timestamp;
  this.sumanId = ++sumanId;

  // initialize
  this.allDescribeBlocks = [];
  this.describeOnlyIsTriggered = false;
  this.deps = null;
  this.numHooksSkipped = 0;
  this.numHooksStubbed = 0;
  this.numBlocksSkipped = 0;

}

I have no idea what the problem is. I tried adding and removing the return type (void) but that did nothing.

Answer

Sean Vieira picture Sean Vieira · Apr 19, 2017

The issue is that ISumanInputs does not include one or more of the properties that you're including in your call or that you haven't properly fulfilled the IsumanInputs interface.

In the extra property case you should get one "extra" error:

Object literal may only specify known properties, and 'anExtraProp' does not exist in type 'ISumanInputs'

In the missing property case you will get a different "extra" error:

Property 'timestamp' is missing in type '{ fileName: string; networkLog: string; outputPath: string; }'.

Interestingly enough, if you move the definition of the argument out of line the extra property case no longer fails:

const data = {
  fileName: "abc",
  networkLog: "",
  outputPath: "",
  timestamp: "",
  anExtraProperty: true
};

new Suman(data);