当前位置:网站首页>Typescript definition type: type 'timeout' cannot be assigned to type 'number';

Typescript definition type: type 'timeout' cannot be assigned to type 'number';

2022-06-12 20:30:00 wendyTan10

Typescript to setTimeout The return value of is defined as number And assign a value to , The following errors will be reported :
error message : You can't type “Timeout” Assign to type “number”;
 Insert picture description here
Locate by clicking , Find out setTimeout Under current project Node.js Interface definition file under :
@types/node index.d.ts, The current definition here is Timerout type

declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;

 Insert picture description here
And the use here :clearTimeout The required parameter is Number type
 Insert picture description here
So what we have to do here is :

//  Method 1 :
//  Defined NodeJs.Timeout The type of 
let timer: null| NodeJS.Timeout = null;
timer = setTimeout(() => {
    }, 1000);
//  When it's cleared , Convert to Number type 
clearTimeout(Number(timer));
//  Method 2 :
//  Can be used directly window.setTimeout() Methods , What is returned is directly Nummber type 
let timer: number;
timer = window.setTimeout(() => {
    }, 1000);
clearTimeout(timer);

原网站

版权声明
本文为[wendyTan10]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206122021201528.html