TypeError: can't convert x to BigInt

JavaScript 異常“無法將 x 轉換為 BigInt”發生在嘗試將 Symbolnullundefined 值轉換為 BigInt 時,或者當期望 BigInt 引數的操作接收到數字時。

訊息

TypeError: Cannot convert null to a BigInt (V8-based)
TypeError: can't convert null to BigInt (Firefox)
TypeError: Invalid argument type in ToBigInt operation (Safari)

錯誤型別

TypeError.

哪裡出錯了?

當使用 BigInt() 函式將值轉換為 BigInt 時,該值將首先轉換為原始值。然後,如果它不是 BigInt、字串、數字和布林值中的一種,則會丟擲錯誤。

某些操作,例如 BigInt.asIntN,要求引數為 BigInt。在這種情況下傳入數字也會丟擲此錯誤。

示例

對無效值使用 BigInt()

js
const a = BigInt(null);
// TypeError: can't convert null to BigInt
const b = BigInt(undefined);
// TypeError: can't convert undefined to BigInt
const c = BigInt(Symbol("1"));
// TypeError: can't convert Symbol("1") to BigInt
js
const a = BigInt(1);
const b = BigInt(true);
const c = BigInt("1");
const d = BigInt(Symbol("1").description);

注意:簡單地使用 String()Number() 將值強制轉換為字串或數字,然後將其傳遞給 BigInt() 通常不足以避免所有錯誤。如果字串不是有效的整數數字字串,則會丟擲 SyntaxError;如果數字不是整數(最值得注意的是 NaN),則會丟擲 RangeError。如果輸入範圍未知,請在使用 BigInt() 之前正確驗證它。

將數字傳遞給期望 BigInt 的函式

js
const a = BigInt.asIntN(4, 8);
// TypeError: can't convert 8 to BigInt
const b = new BigInt64Array(3).fill(3);
// TypeError: can't convert 3 to BigInt
js
const a = BigInt.asIntN(4, 8n);
const b = new BigInt64Array(3).fill(3n);

另見