How to use process.hrtime.bigint

Viewed 1193

When I write

const a = process.hrtime.bigint();

Linting suggests that it is fine, but I see the compilation error

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

Which seems peculiar when I read the docs https://nodejs.org/api/process.html So how can I use bigint() in typescript? My node version is 10.16.2. I am at a loss to understand why typescript doesn't allow this.

1 Answers

Even though BigInt is at stage 4 and can be readily used in recent browser & Node versions, at the time of writing, you will still need to set your TS target config to at least ES2020 or ESNext:

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

As for the actual hrtime.bigint() issue, you might have to either add/update your @types/node type declarations dependency and/or Node itself...

In my own project, I've also used this code below for providing backward compatibility with older Node versions (though w/ obvious lack of precision):

/**
 * 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;
Related