我正在升级一些旧的TypeScript代码以使用最新的编译器版本,我在调用setTimeout时有麻烦。代码期望调用浏览器的setTimeout函数,该函数返回一个数字:

setTimeout(处理程序:(…Args: any[]) => void, timeout: number): number;

但是,编译器将此解析为节点实现,该实现将返回NodeJS。定时器:

setTimeout(回调:(…Args: any[]) => void, ms: number,…args: any[]): NodeJS.Timer;

这段代码没有在节点中运行,但是节点类型被拉入作为对其他东西的依赖(不确定是什么)。

如何指示编译器选择我想要的setTimeout版本?

下面是问题代码:

let n: number;
n = setTimeout(function () { /* snip */  }, 500);

这将产生编译器错误:TS2322:类型'Timer'不能分配给类型'number'。


当前回答

这对我来说非常有效。

type Timer = ReturnType<typeof setTimeout>

const timer: Timer = setTimeout(() => {}, 1000)

其他回答

我通过设置解决了这个问题

tsconfig.json:

{
  "compilerOptions": {
    "skipLibCheck": true,
  }
}

然后创建。d.ts

* .d.ts:

declare namespace NodeJS {
    type Timeout = number;
    type Timer = number;
}

Typescript版本4.2.3

TS2322:类型'Timer'不能分配给类型'number'。

简单的解决方案

ABC:任何;

为了阿斯金

abc = setInterval或abc = setTimeout

我想这取决于您将在哪里运行代码。

如果你的运行时目标是服务器端Node JS,使用:

let timeout: NodeJS.Timeout;
global.clearTimeout(timeout);

如果你的运行时目标是浏览器,使用:

let timeout: number;
window.clearTimeout(timeout);

我遇到了同样的问题,我们的团队决定使用的解决方法是使用“any”作为计时器类型。例如:

let n: any;
n = setTimeout(function () { /* snip */  }, 500);

它将与setTimeout/setInterval/clearTimeout/clearInterval方法的两种实现一起工作。

如果你的目标是setInterval。那么你也可以写成

let timerId: number = setInterval((()=>{
    this.populateGrid(true)
  }) as TimerHandler, 5*1000)
}