应该在打字稿中定义什么类型的超时

pet*_*gan 2 javascript typescript ecmascript-6

我正在尝试在Typescript中编写一个反跳函数,但是不确定设置要分配给的变量的类型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);
    };
}
Run Code Online (Sandbox Code Playgroud)

art*_*tem 5

如果您希望代码在node.js和浏览器环境之间可移植,则可以使用如下返回类型setTimeout

let timeout: ReturnType<typeof setTimeout>;
Run Code Online (Sandbox Code Playgroud)

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