简体   繁体   中英

what type should timeout be defined at in typescript

I am trying to write a debounce function in typescript, but am unsure of what type to set a variable that is assigned to setTimeout . My code looks like this:

function debounced(func: () => void, wait: number) {
    // what type should timeout be here?
    let timeout: any;
    return () => {
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(() => {
            func();
        }, wait);
    };
}

If you want your code to be portable between node.js and browser environment, you can use the return type of setTimeout like this:

let timeout: ReturnType<typeof setTimeout>;

because it's declared to return different types in node and browser.

Typescript prioritizes custom type definitions over default types.

If your tsconfig.json file contains types: node , it is telling Typescript to use the setTimeout(): NodeJS.Timeout found in node_modules/@types/node instead of the default setTimeout(): number method.

"compilerOptions": {
    "types": [
      "node",
      ...
    ]
}

If you don't explicitly need that type option, remove it and this error will go away:

"compilerOptions": {
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM