Javascript 在typescript中应该定义什么类型的超时

Javascript 在typescript中应该定义什么类型的超时,javascript,typescript,ecmascript-6,Javascript,Typescript,Ecmascript 6,我试图在typescript中编写一个去Bounce函数,但不确定设置分配给setTimeout的变量的类型。我的代码如下所示: function debounced(func: () => void, wait: number) { // what type should timeout be here? let timeout: any; return () => { if (timeout) { clearTime

我试图在typescript中编写一个去Bounce函数,但不确定设置分配给
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);
    };
}
let timeout: ReturnType<typeof setTimeout>;

如果希望代码在node.js和浏览器环境之间可移植,可以使用返回类型
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);
    };
}
let timeout: ReturnType<typeof setTimeout>;
let timeout:ReturnType;

因为它声明在节点和浏览器中返回不同的类型。

Typescript将自定义类型定义优先于默认类型

如果tsconfig.json文件包含
types:node
,它会告诉Typescript使用
setTimeout():NodeJS.Timeout
,而不是默认的
setTimeout():number
方法

"compilerOptions": {
    "types": [
      "node",
      ...
    ]
}
如果不明确需要该类型选项,请将其删除,此错误将消失:

"compilerOptions": {
}

如果您只是使用浏览器,显式调用
window.setTimeout
应该可以解决这个问题。

看起来像是
NodeJS.Timeout
可以解决这个问题。这是否正确?如果
timeout
是计时器的ID,那么它就是一个数字。如果我将其设置为
number
我在控制台中看到以下错误-
类型'timeout'不能分配给类型'number'。
该错误告诉您类型是
timeout
。你试过了吗?是的,我试过了-这会产生错误-
找不到名称“Timeout”。
谢谢,我只在浏览器tbh中使用它。然后在浏览器中,它只是
编号
。如果您得到一个关于
类型超时的错误,那么您在某处引用的其他一些代码可能正在拉入node.js类型。