javascript - 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'.
解决方案
添加对 null 的防护:
let timer: null | ReturnType<typeof setTimeout> = null;
timer = setTimeout( myFunc, 1000 );
if (timer) {
clearTimeout(timer);
}
推荐阅读
- javascript - 如何隐藏javascript函数的值?
- python - VS Code Python 交互窗口找不到 Conda Env
- swift - `Control Click` 是否意味着与 macOS 的`右键单击` 相同?
- javascript - 基于日历中的用户输入,突出显示时间和星期几
- javascript - 找不到模块 'mongoose-unique-validator'
- c# - 从 Windows 服务调用 .bat
- postgresql - 非易失性函数中不允许 CREATE TABLE
- javascript - 基于使用javascript的下拉选择填充表中的多个字段,数据应在数组中
- angular - 设置 NGRX8 商店
- c# - DeploymentItem(Path,outputDirectory)在新的单元测试项目中不起作用