首页 > 解决方案 > TS2769:如何使用 TypeScript 中 setTimeout 的返回值修复“clearTimeout”?

问题描述

在“普通”JavaScript 中,我可以执行以下操作:

var timer = setTimeout( myFunc, 1000 );
clearTimout(timer);

但是在 TypeScript 中,setTimeout-Function 有一个奇怪的返回值,因为 clearTimeout 需要一个数字NodeJS.Timer,所以不能使用它。clearTimeout

如何解决?

经过一番研究,我发现了以下类型转换:

let timer: null | ReturnType<typeof setTimeout> = null;
timer = setTimeout( myFunc, 1000 );

然而,调用

clearTimeout(timer)

通过 TypeScript 给出以下错误:

TS2769: No overload matches this call.
  Overload 1 of 2, '(timeoutId: Timeout): void', gave the following error.
    Argument of type 'Timeout | null' is not assignable to parameter of type 'Timeout'.
      Type 'null' is not assignable to type 'Timeout'.
  Overload 2 of 2, '(handle?: number | undefined): void', gave the following error.
    Argument of type 'Timeout | null' is not assignable to parameter of type 'number | undefined'.

标签: javascripttypescript

解决方案


添加对 null 的防护:

let timer: null | ReturnType<typeof setTimeout> = null;
timer = setTimeout( myFunc, 1000 );

if (timer) {
  clearTimeout(timer);
}

推荐阅读