English

JavaScriptの「Cannot mix BigInt」の直し方

​​JavaScript​Chromium,Node.js,トラブルシュート

JavaScript で TypeError: Cannot mix BigInt and other types, use explicit conversions が出たら、BigInt(10n のように末尾に n が付く整数)と普通の数値(Number)を、1つの計算式に混ぜています。+ や / の両側を、BigInt か Number のどちらかにそろえると、エラーは消えます。

Node.js の process.hrtime.bigint() で処理時間をナノ秒で測ってミリ秒に直すときや、BigInt の値を 0 から足し合わせて合計するときに出ます。私は検証環境でこのエラーを起こし、直したあとに消えることを確かめました。

補足

検証環境は Ubuntu 24.04 で、主に Node.js 24.22.3 を使い、比べるために Node.js 22.23.5 でも実行しました。ブラウザは、Playwright から動かした Chromium 158 で、メッセージが同じになることだけを確かめています。Firefox と Safari、TypeScript の型チェックで出るエラー、JSON.stringify で BigInt を文字列にするときのエラーは試していません。出力の中の検証環境の作業フォルダーは /path/to/app に置き換えています。

エラーの全文

処理にかかった時間をミリ秒で表示する、次のスクリプト(elapsed.mjs)を用意しました。

js
// 処理にかかった時間をミリ秒で表示する
const start = process.hrtime.bigint();
await new Promise((resolve) => setTimeout(resolve, 50));
const end = process.hrtime.bigint();

const ms = (end - start) / 1e6;
console.log(`${ms} ms`);

Node.js 24.22.3 で実行すると、次のように出て止まりました(終了コードは1)。

text
$ node elapsed.mjs
file:///path/to/app/elapsed.mjs:6
const ms = (end - start) / 1e6;
                         ^

TypeError: Cannot mix BigInt and other types, use explicit conversions
    at file:///path/to/app/elapsed.mjs:6:26

Node.js v24.22.3

Node.js 22.23.5 でも、違ったのは最後の行のバージョンだけでした。^ の位置と :6:26 は、6行目の / を指しています。

Node.js のドキュメントにある process.hrtime.bigint() の説明のとおり、この関数はナノ秒の時刻を BigInt で返します。end - start は BigInt どうしの引き算なので問題ありません。ところが、1e6 は Number です。BigInt を Number で割ろうとしたところで、エラーになりました。

どんな式でエラーになるのか

BigInt と Number を混ぜた式を、1つずつ実行して結果を表示しました(Node.js 24.22.3。22.23.5 でも同じ結果でした)。

text
1n + 1           => TypeError: Cannot mix BigInt and other types, use explicit conversions
1n - 1           => TypeError: Cannot mix BigInt and other types, use explicit conversions
2n * 3           => TypeError: Cannot mix BigInt and other types, use explicit conversions
10n / 2          => TypeError: Cannot mix BigInt and other types, use explicit conversions
10n % 3          => TypeError: Cannot mix BigInt and other types, use explicit conversions
2n ** 2          => TypeError: Cannot mix BigInt and other types, use explicit conversions
1n + 1.5         => TypeError: Cannot mix BigInt and other types, use explicit conversions
1n & 1           => TypeError: Cannot mix BigInt and other types, use explicit conversions
1n << 1          => TypeError: Cannot mix BigInt and other types, use explicit conversions
1n >>> 0n        => TypeError: BigInts have no unsigned right shift, use >> instead
+1n              => TypeError: Cannot convert a BigInt value to a number
Math.max(1n, 2)  => TypeError: Cannot convert a BigInt value to a number
Math.round(10n)  => TypeError: Cannot convert a BigInt value to a number
1n < 2           => true
2n > 1.5         => true
1n == 1          => true
1n === 1         => false
"id:" + 1n       => "id:1"
`${1n}`          => "1"
1n + "1"         => "11"

足し算や割り算などの計算は、片方が Number だとすべて同じ「Cannot mix BigInt」になりました。MDN の BigInt の解説にも、BigInt は演算で Number と混ぜられず、同じ型にそろえる必要があると書かれています。

先頭の + で数値に直そうとしたり、Math.max や Math.round に渡したりしたときは、メッセージが「Cannot convert a BigInt value to a number」に変わりました。同じ解説にあるとおり、Math の関数は BigInt を受け付けません。>>>(符号なし右シフト)は、同じページの演算子の説明のとおり、BigInt どうしでも使えません。

一方で、< や == で比べる場合は、混ぜてもエラーになりませんでした。ただし 1n === 1 は false です。文字列と + でつなぐ場合も、エラーにならずに文字列になります。

Chromium でも同じです。const total = 10n; console.log(total + 1); を実行したページでは、Cannot mix BigInt and other types, use explicit conversions のエラーが出ました。Firefox や Safari では文面が違い、MDN のエラーの解説ページには、Firefox では can't convert BigInt to number、Safari では Invalid mix of BigInt and other type in addition/multiplication/…. のようなメッセージになると書かれています。

直し方1:BigInt にそろえる

整数の結果で足りるなら、Number の側を BigInt にします。数値の後ろに n を付けると、BigInt の値になります。

js
// 処理にかかった時間をミリ秒で表示する(BigInt のまま割る)
const start = process.hrtime.bigint();
await new Promise((resolve) => setTimeout(resolve, 50));
const end = process.hrtime.bigint();

const ms = (end - start) / 1_000_000n;
console.log(`${ms} ms`, typeof ms);
text
$ node elapsed-bigint.mjs
50 ms bigint

エラーは消え、結果は BigInt の 50 になりました。Node.js 22.23.5 でも同じでした。

BigInt の割り算では、小数点以下が切り捨てられます。10n / 3n は 3n、-10n / 3n は -3n で、Number の 10 / 3 のように 3.3333333333333335 にはなりませんでした。ミリ秒の小数点以下まで見たいときは、次の直し方2を使います。

変数に入った Number を BigInt にするときは、BigInt(x) を使います。ただし、小数は変換できません。

text
BigInt(3)                          => 3n
BigInt(1.5)                        => RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer
BigInt(Math.trunc(1.5))            => 1n
BigInt("42")                       => 42n
BigInt("1.5")                      => SyntaxError: Cannot convert 1.5 to a BigInt
new BigInt(1)                      => TypeError: BigInt is not a constructor

小数が入りうるなら、Math.trunc などで整数にしてから渡します。new を付けて呼ぶとエラーになることも、MDN の BigInt() の解説に書かれています。

直し方2:Number に直してから計算する

小数の結果がほしいときや、Math の関数を使いたいときは、BigInt の側を Number() で Number にしてから計算します。

js
// 処理にかかった時間をミリ秒で表示する(Number に直してから割る)
const start = process.hrtime.bigint();
await new Promise((resolve) => setTimeout(resolve, 50));
const end = process.hrtime.bigint();

const ms = Number(end - start) / 1e6;
console.log(`${ms} ms`, typeof ms);
text
$ node elapsed-number.mjs
50.369003 ms number

エラーは消え、小数点以下まで入った Number になりました(測った時間なので、実行するたびに値は少し変わります)。

Number() に直すときは、大きすぎる値に気をつけます。Number が整数を正確に表せるのは、MDN の Number.MAX_SAFE_INTEGER の解説にあるとおり、9007199254740991 までです。2n ** 53n + 1n(9007199254740993)を Number() に渡すと、1小さい 9007199254740992 になりました。2n ** 53n を渡したときと同じ値です。エラーにはならないので、値がずれたことに気づけません。

注意

データベースの ID のように、もともと大きな値を正確に扱うために BigInt になっている値を Number() にすると、下の桁が変わることがあります。別の ID と同じ値になってしまうこともあるので、そうした値は BigInt のまま計算します。

値の大きさが分からないときは、範囲を確かめてから直すと、ずれた値で計算が進むのを防げます。

js
// BigInt を、正確に表せるときだけ Number に直す
function toSafeNumber(big) {
  if (big > BigInt(Number.MAX_SAFE_INTEGER) || big < BigInt(Number.MIN_SAFE_INTEGER)) {
    throw new RangeError(`${big} は Number では正確に表せません`);
  }
  return Number(big);
}
console.log(toSafeNumber(123n) + 1);
try {
  console.log(toSafeNumber(2n ** 53n + 1n) + 1);
} catch (err) {
  console.log(`${err.name}: ${err.message}`);
}
text
$ node to-safe-number.mjs
124
RangeError: 9007199254740993 は Number では正確に表せません

合計の初期値を 0n にする

BigInt の値を合計するとき、初期値を 0 と書くと Number になるので、BigInt を足したところでエラーになります。

js
// BigInt の配列を合計する(初期値が Number の 0)
const sizes = [1024n, 2048n, 4096n];
let total = 0;
for (const size of sizes) {
  total += size;
}
console.log(total);
text
$ node sum.mjs
file:///path/to/app/sum.mjs:5
  total += size;
           ^

TypeError: Cannot mix BigInt and other types, use explicit conversions
    at file:///path/to/app/sum.mjs:5:12

このあとに Node.js の内部を指す3行と、Node.js v24.22.3 の行が続きます(ここでは省きました)。1回目の 0 + 1024n で止まっています。初期値を 0n にすると、エラーは消えて 7168n と表示されました。reduce で書くときも、sizes.reduce((a, b) => a + b, 0n) のように、2つ目の引数を 0n にすると 7168n になりました。

​Posted by 86