Javascript TS2769:如何修复;clearTimeout“;是否在TypeScript中使用setTimeout的返回值?

Javascript TS2769:如何修复;clearTimeout“;是否在TypeScript中使用setTimeout的返回值?,javascript,typescript,Javascript,Typescript,在“普通”JavaScript中,我可以执行以下操作: var timer = setTimeout( myFunc, 1000 ); clearTimout(timer); 但是在TypeScript中,setTimeout函数有一个奇怪的返回值NodeJS.Timer,它不能用于clearTimeout,因为clearTimeout需要一个数字 如何解决这个问题 经过一些研究,我发现以下类型的铸件: let timer: null | ReturnType<typeof setTim

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

var timer = setTimeout( myFunc, 1000 );
clearTimout(timer);
但是在TypeScript中,setTimeout函数有一个奇怪的返回值
NodeJS.Timer
,它不能用于
clearTimeout
,因为clearTimeout需要一个数字

如何解决这个问题

经过一些研究,我发现以下类型的铸件:

let timer: null | ReturnType<typeof setTimeout> = null;
timer = setTimeout( myFunc, 1000 );
via 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'.

对不起,我不能确认。我今天用Typescript做了以下工作,效果非常好:

private timer: any;

ngOnInit(): void {
 
    this.timer = setTimeout( () => {
        // my code
    }, 1000);

}

stopTimer(): void {
     clearTimeout(this.timer);
}

若您仍然在寻找答案,那个么需要指出的是,您正在从窗口对象而不是节点访问超时

const{setTimeout,cleartimout}=window
const timerId=setTimeout(()=>{
…这里是超时代码
},timeouting(毫秒)
//稍后清除计时器
清除超时(timerID)

但是在TypeScript中,setTimeout函数有一个奇怪的返回值NodeJS.Timer,它不能用于clearTimeout,因为clearTimeout需要一个数字。
clearTimeout接受由
setTimeout
返回的值。您指定Timer可以为null,但重载1(获取超时)不接受null。要么在一条语句中赋值,要么使用空保护(if语句)“但在TypeScript中,setTimeout函数有一个奇怪的返回值
NodeJS.Timer
”-否。它在Node.js中有该返回类型,并且您似乎已将TypeScript配置为假定节点环境。在节点中,
clearTimeout
也接受这样一个计时器对象。@是否删除
tsconfig.json
的内容?
private timer: any;

ngOnInit(): void {
 
    this.timer = setTimeout( () => {
        // my code
    }, 1000);

}

stopTimer(): void {
     clearTimeout(this.timer);
}