node.js - 如何使用 process.hrtime.bigint

标签 node.js typescript

当我写作时

const a = process.hrtime.bigint();

Linting 表明它没问题,但我看到编译错误

error TS2339: Property 'bigint' does not exist on type 'HRTime'.

当我阅读文档时,这看起来很奇怪 https://nodejs.org/api/process.html 那么如何在 typescript 中使用bigint()呢?我的 Node 版本是10.16.2。我不明白为什么 typescript 不允许这样做。

最佳答案

尽管 BigInt 处于第 4 阶段并且可以在最新的浏览器和 Node 版本中轻松使用,但在撰写本文时,您仍然需要设置 TS target config至少到 ES2020ESNext:

{
    "compilerOptions": {
        "target": "ESNext"
        ...
    }
}

对于实际的 hrtime.bigint() 问题,您可能必须添加/更新您的 @types/node 类型声明依赖项和/或 Node 本身。 ..

在我的own project ,我还使用下面的代码来提供与旧 Node 版本的向后兼容性(尽管明显缺乏精度):

/**
 * If available, returns wrapper for `process.hrtime.bigint()` else
 * falls back to `Date.now()`. In all cases, returns a nanosec-scale
 * timestamp, either as `bigint` or `number`.
 */
export const now =
    typeof BigInt !== "undefined"
        ? typeof process !== "undefined" &&
          typeof process.hrtime !== "undefined" &&
          typeof process.hrtime.bigint === "function"
            ? () => process.hrtime.bigint()
            : () => BigInt(Date.now() * 1e6)
        : () => Date.now() * 1e6;

关于node.js - 如何使用 process.hrtime.bigint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61007382/

相关文章:

node.js - npm run 不提供脚本作为建议

javascript - 使用nodejs/express 出现意外的换行符

javascript - TypeError 无法读取未定义的属性 "length"- angular 4

javascript - 如何在 typescript 中使用 angular4 隐藏导航选项卡

node.js - res.format() 在 Express 4.x 中不起作用

node.js - ARM 上的 NodeJS 运行一个空文件需要 26 秒

javascript - HTTP 响应正文的 Node.js unicode 问题

arrays - TypeScript:有没有办法使用 typeof 运算符获得类型数组?

Angular - 动态加载图像

javascript - 如何将用户关键字添加到 VS2013 TypeScript 语言文本编辑器?