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:
let foo: bigint = BigInt(100); // the BigInt function
let bar: bigint = 100n; // a BigInt literal
// *Slaps roof of fibonacci function*
// This bad boy returns ints that can get *so* big!
function fibonacci(n: bigint) {
let result = 1n;
for (let last = 0n, i = 0n; i < n; i++) {
const current = result;
result += last;
last = current;
}
return result;
}
fibonacci(10000n)
While you might imagine close interaction between number
and bigint
, the two are separate domains.
declare let foo: number;
declare let bar: bigint;
foo = bar; // error: Type 'bigint' is not assignable to type 'number'.
bar = foo; // error: Type 'number' is not assignable to type 'bigint'.
As specified in ECMAScript, mixing number
s and bigint
s in arithmetic operations is an error.You’ll have to explicitly convert values to BigInt
s.
console.log(3.141592 * 10000n); // error
console.log(3145 * 10n); // error
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"
.Thus, TypeScript correctly narrows using typeof
as you’d expect.
function whatKindOfNumberIsIt(x: number | bigint) {
if (typeof x === "bigint") {
console.log("'x' is a bigint!");
}
else {
console.log("'x' is a floating-point number");
}
}
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.