TS. With the keyword 'new', only the void function can be called.

I get this strange error from TypeScript:

"With the keyword" new ", only the void function can be called.

What?

enter image description here

The constructor function looks simple:

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 did nothing.

+5
source share
2 answers

The problem is that ISumanInputs does not include one or more properties that you include in your call, or that you have incorrectly executed the ISumanInputs interface.

In the case of additional property, you should get one "additional" error:

An object literal can specify only known properties, and 'anExtraProp' does not exist in the type 'ISumanInputs'

If there is no property, you will get another "additional" error:

Missing property timestamp 'type' {fileName: string; networkLog: string; outputPath: string; } ".

Interestingly, if you move the argument definition outside the line, the extra property case will no longer fail:

 const data = { fileName: "abc", networkLog: "", outputPath: "", timestamp: "", anExtraProperty: true }; new Suman(data); 
+3
source

As Sean noted, this is a less obvious consequence of type mismatch in arguments.

In case you are interested in a deeper reason: when function arguments are not checked by typecheck, tsc returns the return type for the special type never (overrides the void that you specified). And new with such a function will call TS2350 Only a void function can...

This snippet can run TS2350 without invalid arguments.

 function Ctor(): never { throw "never return"; } const v = new Ctor(); 
+3
source

Source: https://habr.com/ru/post/1266887/


All Articles