🛡

[TypeScript] 非常に大きな整数はbigint型を使う

に公開
2026/09/25

🌱 はじめに

この記事では、TypeScript の bigint 型 をまとめています。

🌱 結論

🌱 1. number 型で安全な整数の範囲を超えるとどうなるか

console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991

// 安全な整数の範囲を超えると、異なる値のはずが同じ値として扱われる
console.log(2 ** 53 === 2 ** 53 + 1); // true

🌱 2. bigint 型で大きな整数を扱う

const big: bigint = 2n ** 53n;

// 範囲を超えても正確に計算できる
console.log(big + 1n); // 9007199254740993n

🌱 3. bigint 型に number 型の値は代入できない

// Type 'number' is not assignable to type 'bigint'.
const num: bigint = 100;

小さい値でも、bigint型として扱う場合は100nのように末尾にnを付けます。

const num: bigint = 100n;

🌱 4. bigint と number は混在させて計算できない

// Operator '+' cannot be applied to types '1n' and '1'.
const sum = 1n + 1;

計算する場合は、BigInt()でbigintにそろえます(Number()でnumberにそろえると、安全な整数の範囲外では精度が失われることがあります)。

const sum = 1n + BigInt(1); // 2n
GitHubで編集を提案

Discussion