Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Primitive and Special Types

The TypeScript bigint type

Reference for bigint in TypeScript: n literals, arithmetic rules, mixing with number errors, BigInt() conversion, asIntN, JSON and the ES2020 target.

bigint is the primitive type for whole numbers of any size. A literal ends in n (123n), and values are created from other types with the BigInt() function. Where number loses exactness above 2^53, a bigint stays exact until memory runs out.

bigint requires a compilation target of ES2020 or later (the default in modern setups). It does not mix with number in arithmetic: you must convert explicitly.

TypeScript
const big: bigint = 9007199254740993n;
const sum: bigint = big + 2n;

Try it

TypeScript Exact big integer math

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Converting and comparing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
let a: bigint = 10n;
const b = BigInt(value);          // value: number | string | boolean | bigint
type Id = bigint;
Part Description
123n, 0xffn Literals. The n suffix is required; there is no decimal form like 1.5n.
BigInt(x) Converts an integral number, a numeric string, a boolean or a bigint. Fractions and NaN throw RangeError; invalid strings throw SyntaxError. Not used with new.
BigInt.asIntN(bits, v), asUintN Wrap to a signed or unsigned width.

Mixing the types is a compile error:

TypeScript
const total = 1n + 1; // error TS2365: Operator '+' cannot be applied to types 'bigint' and 'number'.

Usage notes

  • Operators. + - * / % ** and bitwise operators work between bigints. Unary + is not allowed, and >>> throws, because there is no fixed width.
  • Division truncates toward zero and has no fractional part.
  • Comparison with number works with < and >. == and === between the two types are reported as errors (TS2367), even though 10n == 10 is true at runtime.
  • Literal types. 10n is a bigint literal type, usable in unions such as 0n | 1n.
  • No Math. Math.max(1n, 2n) throws; write a small helper with comparisons.
  • Performance. Bigints are slower than numbers; use them only when you need the range (ids, hashes, counters, finance in minor units).
  • JSON throws TypeError on bigint unless you supply a replacer.
  • Target. With a target below ES2020 the compiler reports that BigInt literals are not available (TS2737).