Ale*_*lls 10 node.js typescript typescript2.0
我从TypeScript得到这个奇怪的错误:
"只能使用'new'关键字调用void函数."
什么?
构造函数,看起来像:
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;
}
Run Code Online (Sandbox Code Playgroud)
我不知道问题是什么.我尝试添加和删除返回类型(void),但没有做任何事情.
问题是ISumanInputs您的通话中不包含一个或多个属性,或者您没有正确实现该IsumanInputs接口。
在额外属性的情况下,您应该得到一个“额外”错误:
对象文字只能指定已知的属性,并且'isumanInputs'类型中不存在'anExtraProp'
在缺少属性的情况下,您将收到另一个“额外”错误:
类型'{fileName:string;类型中缺少属性'timestamp'。networkLog:字符串;outputPath:字符串; }'。
有趣的是,如果您将参数的定义移出行,则额外的属性情况将不再失败:
const data = {
fileName: "abc",
networkLog: "",
outputPath: "",
timestamp: "",
anExtraProperty: true
};
new Suman(data);
Run Code Online (Sandbox Code Playgroud)
正如Sean所指出的,这是参数中类型不匹配的不太明显的结果。
如果有更深层的原因引起您的兴趣:当不对函数的参数进行tsc类型检查时,则将返回类型推断为特殊类型never(覆盖void您指定的类型)。并new带有这样的功能会引起TS2350 Only a void function can...。
该代码片段可以触发TS2350,而无需使用错误的参数。
function Ctor(): never {
throw "never return";
}
const v = new Ctor();
Run Code Online (Sandbox Code Playgroud)