javascript エラー「TypeError: Invalid mix of BigInt and other type in addition.」の解決方法

javascript エラー「TypeError: Invalid mix of BigInt and other type in addition.」の解決方法

javascriptで、エラー「TypeError: Invalid mix of BigInt and other type in addition.」が発生した場合の原因と解決方法を記述してます。

環境

  • OS macOS Big Sur
  • ブラウザ safari 15.5

エラー内容

以下のコードで発生。

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

エラーメッセージ

TypeError: Invalid mix of BigInt and other type in addition.

画像

原因

BigInt以外と演算しようとしているため

解決方法

BigIntにキャストするか、

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

数値リテラルにキャストする

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