TypeError: can't convert BigInt to number
当算术运算涉及 BigInt 和 Number 值的混合时,会发生 JavaScript 异常“无法将 BigInt 转换为数字”。
消息
TypeError: Cannot convert a BigInt value to a number (V8-based) TypeError: Cannot mix BigInt and other types, use explicit conversions (V8-based) TypeError: BigInts have no unsigned right shift, use >> instead (V8-based) TypeError: can't convert BigInt to number (Firefox) TypeError: Conversion from 'BigInt' to 'number' is not allowed. (Safari) TypeError: Invalid mix of BigInt and other type in addition/multiplication/…. (Safari) TypeError: BigInt does not support >>> operator (Safari)
错误类型
哪里出错了?
算术运算符的两边必须都是 BigInt,或者都不是 BigInt。如果操作涉及 BigInt 和数字的混合,则结果应该是 BigInt 还是数字是模棱两可的,因为两种情况下都可能存在精度损失。
当 BigInt 通过数字强制转换过程隐式转换为数字时,也会发生此错误。例如,如果将 BigInt 传递给需要数字的内置方法。
如果在两个 BigInt 之间使用无符号右移运算符 (>>>),也可能发生此错误。在 Firefox 中,消息是相同的:“无法将 BigInt 转换为数字”。
示例
在操作中混合数字和 BigInt
js
const sum = 1n + 1;
// TypeError: can't convert BigInt to number
而是明确地将其中一侧强制转换为 BigInt 或数字。
js
const sum = 1n + BigInt(1);
const sum2 = Number(1n) + 1;
在 BigInt 上使用无符号右移
js
const a = 4n >>> 2n;
// TypeError: can't convert BigInt to number
改用正常的右移。
js
const a = 4n >> 2n;