BigInt 和 Number 转换
在 JavaScript 中处理数字时,有两种基本类型可供选择 - BigInt 和 Number。人们可能会期望从“较小”类型到“较大”类型的隐式转换,但这在 JavaScript 中不是这种情况。
预期
当计算 BigInt 和 Number 的某些组合时,用户可能会期望从 Number 到 BigInt 的隐式转换,如下例所示:
const number = 16n + 32; // DOESN'T WORK
// Expected: Evaluates to 48n
实际行为
同时对 BigInt 和 Number 进行操作的表达式会抛出错误:
const number = 16n + 32;
// Throws "TypeError: Cannot mix BigInt and other types, use explicit conversions"
为什么上述情况需要显式转换?
或者换句话说,这种设计背后的原因是什么?
最佳答案
这记录在原始 BigInt 提案中:https://github.com/tc39/proposal-bigint/blob/master/README.md#design-goals-or-why-is-this-like-this
When a messy situation comes up, this proposal errs on the side of throwing an exception rather than rely on type coercion and risk giving an imprecise answer.
关于javascript - 为什么 BigInt 要求从 Number 进行显式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57996921/