当我写作时
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至少到 ES2020
或 ESNext
:
{
"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/