javascript エラー「Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions」の解決方法

javascript エラー「Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions」の解決方法

javascriptで、エラー「Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions」が発生した場合の原因と解決方法を記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.66

エラー内容

以下のコードで発生。

console.log( 2n + 2n + 1 )

エラーメッセージ

Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions

画像

firefox(バージョン102)では、以下のエラーとなります。

Uncaught TypeError: can't convert BigInt to number

画像

原因

BigIntは、BigInt同士でないと演算できないため

解決方法

全てBigIntで演算するか、

console.log( 2n + 2n + 1n ) // 5n

キャストして演算する

console.log( Number(2n) + Number(2n) + 1 ) // 5