【问题标题】:what type should timeout be defined at in typescript在打字稿中应该定义什么类型的超时
【发布时间】: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


【解决方案1】:

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

let timeout: ReturnType<typeof setTimeout>;

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

【讨论】:

  • 谢谢,我只在浏览器中使用它。
  • 然后在浏览器中,它只是number。如果您收到关于 Type Timeout 的错误,那么您在某处引用的其他代码可能正在拉入 node.js 类型。
【解决方案2】:

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

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

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

如果您没有明确需要该类型选项,请将其删除,此错误将消失:

"compilerOptions": {
}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2020-05-31
      • 2021-12-02
      • 2021-07-06
      • 2018-01-18
      • 2023-02-07
      • 2021-09-27
      • 1970-01-01
      • 2020-05-07
      • 2016-11-06
      相关资源
      最近更新 更多