BigInt

BigInts are part of an upcoming proposal in ECMAScript that allow us to model theoretically arbitrarily large integers.TypeScript 3.2 brings type-checking for BigInts, as well as support for emitting BigInt literals when targeting esnext.

BigInt support in TypeScript introduces a new primitive type called the bigint (all lowercase).You can get a bigint by calling the BigInt() function or by writing out a BigInt literal by adding an n to the end of any integer numeric literal:

  1. let foo: bigint = BigInt(100); // the BigInt function
  2. let bar: bigint = 100n; // a BigInt literal
  3. // *Slaps roof of fibonacci function*
  4. // This bad boy returns ints that can get *so* big!
  5. function fibonacci(n: bigint) {
  6. let result = 1n;
  7. for (let last = 0n, i = 0n; i < n; i++) {
  8. const current = result;
  9. result += last;
  10. last = current;
  11. }
  12. return result;
  13. }
  14. fibonacci(10000n)

While you might imagine close interaction between number and bigint, the two are separate domains.

  1. declare let foo: number;
  2. declare let bar: bigint;
  3. foo = bar; // error: Type 'bigint' is not assignable to type 'number'.
  4. bar = foo; // error: Type 'number' is not assignable to type 'bigint'.

As specified in ECMAScript, mixing numbers and bigints in arithmetic operations is an error.You’ll have to explicitly convert values to BigInts.

  1. console.log(3.141592 * 10000n); // error
  2. console.log(3145 * 10n); // error
  3. console.log(BigInt(3145) * 10n); // okay!

Also important to note is that bigints produce a new string when using the typeof operator: the string "bigint".Thus, TypeScript correctly narrows using typeof as you’d expect.

  1. function whatKindOfNumberIsIt(x: number | bigint) {
  2. if (typeof x === "bigint") {
  3. console.log("'x' is a bigint!");
  4. }
  5. else {
  6. console.log("'x' is a floating-point number");
  7. }
  8. }

We’d like to extend a huge thanks to Caleb Sander for all the work on this feature.We’re grateful for the contribution, and we’re sure our users are too!

Caveats

As we mentioned, BigInt support is only available for the esnext target.It may not be obvious, but because BigInts have different behavior for mathematical operators like +, -, *, etc., providing functionality for older targets where the feature doesn’t exist (like es2017 and below) would involve rewriting each of these operations.TypeScript would need to dispatch to the correct behavior depending on the type, and so every addition, string concatenation, multiplication, etc. would involve a function call.

For that reason, we have no immediate plans to provide downleveling support.On the bright side, Node 11 and newer versions of Chrome already support this feature, so you’ll be able to use BigInts there when targeting esnext.

Certain targets may include a polyfill or BigInt-like runtime object.For those purposes you may want to add esnext.bigint to the lib setting in your compiler options.