Node.js 如何使用process.hrtime.bigint
当我写作时Node.js 如何使用process.hrtime.bigint,node.js,typescript,Node.js,Typescript,当我写作时 const a = process.hrtime.bigint(); 林廷认为这很好,但我看到了编译错误 error TS2339: Property 'bigint' does not exist on type 'HRTime'. 当我读文件的时候,这看起来很奇怪 那么如何在typescript中使用bigint()?我的节点版本是10.16.2。我不明白为什么typescript不允许这样做 即使BigInt处于第4阶段,并且可以在最新的浏览器和节点版本中使用,在撰写本文时
const a = process.hrtime.bigint();
林廷认为这很好,但我看到了编译错误
error TS2339: Property 'bigint' does not exist on type 'HRTime'.
当我读文件的时候,这看起来很奇怪
那么如何在typescript中使用bigint()?我的节点版本是10.16.2。我不明白为什么typescript不允许这样做 即使
BigInt
处于第4阶段,并且可以在最新的浏览器和节点版本中使用,在撰写本文时,您仍然需要将您的设置为至少ES2020
或ESNext
:
{
"compilerOptions": {
"target": "ESNext"
...
}
}
至于实际的hrtime.bigint()
问题,您可能需要添加/更新@types/node
类型声明依赖项和/或节点本身
在我的中,我还使用了下面的代码来提供与较旧节点版本的向后兼容性(尽管明显缺乏精确性):
@很好,刚刚更新/修复了代码(忘记将
Date.now()缩放到纳秒级)。你也能接受这个答案吗?
/**
* 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;