【发布时间】:2022-01-10 08:59:20
【问题描述】:
我在 TypeScript 上遇到了一个奇怪的问题。我最近了解了void ... 运算符,因为我需要应用它,所以eslint 不会报告no-floating-promises。然而,这个特殊的 sn-p 不知何故导致了一个问题,我无法在 TypeScript 操场上重现:
class A {
async a() {}
async onTickAsync(repeat: boolean) {
try {
await this.a();
} catch(e) {
console.error(e);
} finally {
if (repeat) {
window.setTimeout(() => void this.onTickAsync(true), 200);
}
}
}
}
VS Code 会报这个错误:
TS7011:缺少返回类型注释的函数表达式隐式具有“任意”返回类型。
但是,TS Playground 上无法重现该问题。 VS Code 和 Playground 都使用 TypeScript 4.5.4。这是我的tsconfig.json:
{
"compileOnSave": true,
"compilerOptions": {
"noImplicitAny": true,
"noEmitOnError": true,
"sourceMap": true,
"target": "ESNext",
"module": "ESNext"
},
"exclude": [
"node_modules"
]
}
我知道可以通过添加: void返回类型或删除void操作或删除noImplicitAny来修复它:
window.setTimeout((): void => void this.onTickAsync(true), 200);
我想问:是什么导致了错误?为什么它只发生在我的 IDE/本地而不是操场上?
为了确保这不仅仅是因为 VS Code,我还在单独的终端上运行了 tsc --version 和 tsc:
tsc --showConfig 输出:
PS C:\Users\lukev\Downloads\Temp> tsc --showConfig
{
"compilerOptions": {
"noImplicitAny": true,
"noEmitOnError": true,
"sourceMap": true,
"target": "esnext",
"module": "esnext"
},
"files": [
"./test.ts"
],
"exclude": [
"node_modules"
],
"compileOnSave": true
}
这也很有趣,它不会发生在其他功能上。例如,这不会产生任何错误。这似乎与window.setTimeout 有关。例如,我发现Function 类型和() => void 之间存在一些不同):
class A {
doSomething1(_: Function) { }
doSomething2(_: () => any) { }
doSomething3(_: () => void) { }
async a() { }
async onTickAsync(repeat: boolean) {
// Only this one produces error
this.doSomething1(() => void this.onTickAsync(true));
this.doSomething2(() => void this.onTickAsync(true));
this.doSomething3(() => void this.onTickAsync(true));
}
}
【问题讨论】:
-
@LukeVo 您会在问题中包含
tsc --showConfig的输出吗? -
@jsejcksn 不知道该命令。已添加。
-
@T.J.Crowder 和你的截图一模一样。
4.5.4 — TypeScript version。另外我认为这不是由于 VS Code,因为它也发生在独立终端上。 -
嗯,这似乎真的很确定。 :-)(我误解了你之前关于单独运行
tsc的评论;我现在明白了。)谢谢! -
我发现它与
setTimeout使用TimerHandler = string | Function作为其参数类型有关。 Playground 和我的lib.dom.d.ts之间可能有什么不同吗?
标签: typescript function void any