TypeError: 不能混合 BigInt 与其他类型
快速摘要
你把 BigInt 与 Number 相加或比较——JavaScript 不会隐式转换,运算失败。
为什么发生
用 +、-、*、/ 把 BigInt 与 Number 相加
从不同来源分别读取 BigInt 和 Number 却未转换
对 BigInt 调用只接受 Number 的 Math 方法
最小示例
✗ 错误代码
const big = 10n;
const sum = big + 5; // TypeError: Cannot mix BigInt and other types
console.log(sum);✓ 修复代码
const big = 10n;
const sum = big + BigInt(5); // 15n
console.log(sum);不能直接把 BigInt 与 Number 相加。用 BigInt(5) 把 5 转为 BigInt 后两操作数类型一致。
如何诊断
阅读 TypeError: 'Cannot mix BigInt and other types'
用 typeof 检查两个操作数以识别 BigInt
查找接收 BigInt 参数的 Math.* 调用
如何修复
算术前把两个操作数转为同一类型
用 BigInt(n) 把 Number 转 BigInt,或用 Number(b) 反向转换
避免对 BigInt 用 Math 方法——使用 BigInt 原生运算
如何预防
每次计算选定一种数字类型,在边界处转换
用 TypeScript 的 bigint 与 number 类型保持分离