Al Fahad
Al Fahad

Reputation: 2568

Unable to use BigInt in typescript version 3.1.6. error TS2304: Cannot find name 'BigInt'

I want to use BigInt in Typescript

    private AND = (left: BitwiseNumber, right: BitwiseNumber) => {
     return BigInt(left) & BigInt(right);
    }

But it gave me this error:

src/dir/file-name.ts(190,10): error TS2304: Cannot find name 'BigInt'.

To solve this checked answer to this question which cited this document and suggested me to add "target": "esnext" & "lib": ["esnext.bigint"] in file tsconfig.json.

but my tsconfig.json file already has these values in target and lib as shown below:

    "target": "es2018",
    "lib": ["es2018"],

Now if I change value of target from es-2018 to esnext. It start throwing other errors. So, My question can I still use BigInt in version 3.1.6? If Not is there any alternate for BigInt in this version?

My Typescript version is 3.1.6

Upvotes: 2

Views: 7422

Answers (1)

jcalz
jcalz

Reputation: 328387

As mentioned in the comments, BigInt support was added to TypeScript with the release of TypeScript 3.2.

If you are unable to upgrade (which is unfortunate, as TypeScript changes quickly enough for this to be a significant source of technical debt), then you cannot use BigInt directly.

One approach here is to use a third-party arbitrary-precision integer library instead. This cannot be a completely transparent replacement; it's not possible to polyfill syntax. So you won't be able to use BigInt literals like 123n or the overloaded numeric operators like BigInt(3) * BigInt(5). Instead you'll need to use methods or functions which give such behavior.

I don't think this is the place to advocate for a particular library, so I'll just use the one I found first when searching: BigInteger.js, published in npm as big-integer:

import bigInt from "big-integer";

Then your above code will need to use the and() method for bitwise-and instead of the & operator:

  private AND = (left: BitwiseNumber, right: BitwiseNumber) => {
    return bigInt(left).and(bigInt(right));
  };

Okay, hope this helps; good luck!

Playground link to code

Upvotes: 3

Related Questions