Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using BigInt in TypeScript

Tags:

typescript

I believe I should be able to use BigInt now in TypeScript...but changing some code base to use it and I get "Cannot find name 'BigInt'. (2304)" any thought on why I am getting this error?

$ cat test.ts 
let x = BigInt(123)
console.log(x.toString())

$ tsc test.ts 
test.ts:1:9 - error TS2304: Cannot find name 'BigInt'.

1 let x = BigInt(123)
          ~~~~~~


Found 1 error.

How do I start using BigInt now within TypeScript?

like image 466
Finlay Weber Avatar asked Dec 23 '19 13:12

Finlay Weber


People also ask

How do you use BigInt in typescript?

You'll have to explicitly convert values to BigInt s. console. log(BigInt(3145) * 10n); // okay! Also important to note is that bigint s produce a new string when using the typeof operator: the string "bigint" .

How do you declare BigInt?

A BigInt value, also sometimes just called a BigInt, is a bigint primitive, created by appending n to the end of an integer literal, or by calling the BigInt() function (without the new operator) and giving it an integer value or string value.

What is the use of BigInt?

BigInt is a new data type intended for use when integer values are larger than the range supported by the Number data type. This data type allows us to safely perform arithmetic operations on large integers, represent high-resolution timestamps, use large integer IDs, and more without the need to use a library.


Video Answer


3 Answers

BigInt support has been added on TypeScript 3.2; make sure your version is compatible.

But on top of that, you need to decide how BigInt will be supported on the context of your script - will you provide polyfills, or will you only run your script on environments that are guaranteed to have BigInt support?

This means you will need esnext as your build target (likely on tsconfig.json's target field), since BigInt is not compatible with previous ECMAScript versions.

If you do include a BigInt polyfill, you can use esnext.bigint as part of the lib field during transpilation. This adds the needed definitions to the process.

like image 113
zeh Avatar answered Oct 19 '22 03:10

zeh


It works for me to add esnext.bigint in lib .

{
  "compilerOptions": {
    "lib": ["es6","esnext.bigint"]
  }
}
like image 2
宪平杨 Avatar answered Oct 19 '22 05:10

宪平杨


In my case, I should be add "node" to types in my tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "outDir": "build/module",
    "module": "esnext",
    "types": ["node"]
  },
  "exclude": [
    "node_modules/**"
  ]
}
like image 1
whalemare Avatar answered Oct 19 '22 04:10

whalemare