TS - 只能使用 'new' 关键字调用 void 函数
TS - Only a void function can be called with the 'new' keyword
我从 TypeScript 收到这个奇怪的错误:
"Only a void function can be called with the 'new' keyword."
什么?
构造函数,看起来像:
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;
}
我不知道问题出在哪里。我尝试添加和删除 return 类型(void),但什么也没做。
问题是 ISumanInputs
不包含您在调用中包含的一项或多项属性 或 您没有正确满足IsumanInputs
界面。
在额外的 属性 情况下,您应该得到一个 "extra" 错误:
Object literal may only specify known properties, and 'anExtraProp' does not exist in type 'ISumanInputs'
在缺少 属性 的情况下,您将得到一个不同的 "extra" 错误:
Property 'timestamp' is missing in type '{ fileName: string; networkLog: string; outputPath: string; }'.
有趣的是,如果您将参数的定义移出行外,额外的 属性 案例将不再失败:
const data = {
fileName: "abc",
networkLog: "",
outputPath: "",
timestamp: "",
anExtraProperty: true
};
new Suman(data);
正如 Sean 所指出的,这是参数类型不匹配的不太明显的结果。
如果您对更深层次的原因感兴趣:当函数的参数不进行类型检查时,tsc
将 return 类型推断为特殊类型 never
(重写 void
你指定的)。而new
这样的函数会造成TS2350 Only a void function can...
.
此代码片段可以在没有错误参数的情况下触发 TS2350。
function Ctor(): never {
throw "never return";
}
const v = new Ctor();
我从 TypeScript 收到这个奇怪的错误:
"Only a void function can be called with the 'new' keyword."
什么?
构造函数,看起来像:
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;
}
我不知道问题出在哪里。我尝试添加和删除 return 类型(void),但什么也没做。
问题是 ISumanInputs
不包含您在调用中包含的一项或多项属性 或 您没有正确满足IsumanInputs
界面。
在额外的 属性 情况下,您应该得到一个 "extra" 错误:
Object literal may only specify known properties, and 'anExtraProp' does not exist in type 'ISumanInputs'
在缺少 属性 的情况下,您将得到一个不同的 "extra" 错误:
Property 'timestamp' is missing in type '{ fileName: string; networkLog: string; outputPath: string; }'.
有趣的是,如果您将参数的定义移出行外,额外的 属性 案例将不再失败:
const data = {
fileName: "abc",
networkLog: "",
outputPath: "",
timestamp: "",
anExtraProperty: true
};
new Suman(data);
正如 Sean 所指出的,这是参数类型不匹配的不太明显的结果。
如果您对更深层次的原因感兴趣:当函数的参数不进行类型检查时,tsc
将 return 类型推断为特殊类型 never
(重写 void
你指定的)。而new
这样的函数会造成TS2350 Only a void function can...
.
此代码片段可以在没有错误参数的情况下触发 TS2350。
function Ctor(): never {
throw "never return";
}
const v = new Ctor();