javascript エラー「Uncaught TypeError: Cannot convert a BigInt value to a number」の解決方法

javascript エラー「Uncaught TypeError: Cannot convert a BigInt value to a number」の解決方法

javascriptで、エラー「Uncaught TypeError: Cannot convert a BigInt value to a number」が発生した場合の原因と解決方法を記述してます。「Math.abs」に「bigint」を使用した場合に発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。

環境

  • OS windows11 pro 64bit
  • ブラウザ chrome 110.0.5481.78

エラー内容

以下の、「Math.abs」に「bigint」型を使用した際に発生。

let x = 5n;

Math.abs(x);

エラーメッセージ

Uncaught TypeError: Cannot convert a BigInt value to a number
    at Math.abs (<anonymous>)

画像

firefox107の場合では、以下のエラーが発生します。

Uncaught TypeError: can't convert BigInt to number

画像

safari15.5では、以下のエラーとなります。

[Error] TypeError: Cannot access invalid private field (evaluating 'this.#n = n')

画像

原因

「Math.abs」は「bigint」を使用できないため

解決方法

「Number」に変換して使用する。

let x = 5n;

let result = Math.abs(typeof x === 'bigint' ? Number(x) : x);

console.log(result); // 5

または、「bigint」が含まているか判定してから使用する方法もあります。

let x = 5n;

let result = typeof x !== 'bigint' ? Math.abs(x) : '無効な値が含まれています';

console.log(result); // 無効な値が含まれています

変換する関数を自作する方法もあります。

function getAbs(n){
  return n < 0 ? -n : n
}

console.log( getAbs(10n) )  // 10n
console.log( getAbs(-10n) )  // 10n