TypeError: can't convert x to BigInt
JavaScript 异常“无法将 x 转换为 BigInt”发生在尝试将 Symbol、null 或 undefined 值转换为 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)
错误类型
哪里出错了?
当使用 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);