Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 897
Alexander Mills Avatar asked Apr 19 '17 00:04

Alexander Mills


People also ask

What is a void function?

Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.

Can a void function return a string?

void means the function does not return any value.

How do I terminate a void function?

Use return; instead of return(0); to exit a void function.


1 Answers

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);
like image 97
Sean Vieira Avatar answered Sep 23 '22 13:09

Sean Vieira