类型错误:无法将 BigInt 转换为数字

当算术运算涉及 BigIntNumber 值的混合时,会发生 JavaScript 异常 "无法将 BigInt 转换为数字"。

¥The JavaScript exception "can't convert BigInt to number" occurs when an arithmetic operation involves a mix of BigInt and Number values.

信息

¥Message

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: Invalid mix of BigInt and other type in addition/multiplication/…. (Safari)
TypeError: BigInt does not support >>> operator (Safari)

错误类型

¥Error type

TypeError

什么地方出了错?

¥What went wrong?

算术运算符的两侧必须都是 BigInt,或者都不是。如果运算涉及 BigInt 和数字的混合,则结果应该是 BigInt 还是数字是不明确的,因为在这两种情况下都可能会损失精度。

¥The two sides of an arithmetic operator must both be BigInts or both not. If an operation involves a mix of BigInts and numbers, it's ambiguous whether the result should be a BigInt or number, since there may be loss of precision in both cases.

如果在两个 BigInt 之间使用 无符号右移运算符 (>>>),也可能会发生该错误。在 Firefox 中,消息是相同的:"无法将 BigInt 转换为数字"。

¥The error can also happen if the unsigned right shift operator (>>>) is used between two BigInts. In Firefox, the message is the same: "can't convert BigInt to number".

示例

¥Examples

在运算中混合数字和 BigInt

¥Mixing numbers and BigInts in operations

js
const sum = 1n + 1;
// TypeError: can't convert BigInt to number

相反,显式地将一侧强制为 BigInt 或数字。

¥Instead, explicitly coerce one side to a BigInt or number.

js
const sum = 1n + BigInt(1);
const sum2 = Number(1n) + 1;

在 BigInt 上使用无符号右移

¥Using unsigned right shift on BigInts

js
const a = 4n >>> 2n;
// TypeError: can't convert BigInt to number

请改用正常的右移。

¥Use normal right shift instead.

js
const a = 4n >> 2n;

也可以看看

¥See also