【发布时间】:2019-07-22 21:44:53
【问题描述】:
我正在尝试在 typescript 中编写一个 debounce 函数,但不确定要设置分配给 setTimeout 的变量的类型。我的代码如下所示:
function debounced(func: () => void, wait: number) {
// what type should timeout be here?
let timeout: any;
return () => {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
func();
}, wait);
};
}
【问题讨论】:
-
看起来像
NodeJS.Timeout做到了。这是正确的吗? -
如果
timeout是定时器的ID,那么它是一个数字。 -
如果我将其设置为
number我会在控制台中看到以下错误 -Type 'Timeout' is not assignable to type 'number'.????♂️ -
那个错误告诉你类型是
Timeout。你试过吗? -
是的,我已经尝试过了 - 这给出了错误 -
Cannot find name 'Timeout'.
标签: javascript typescript ecmascript-6