Why BigInt demand explicit conversion from Number?

扶醉桌前 提交于 2021-02-10 07:54:23

问题


BigInt and Number conversions

When working with numbers in JavaScript there are two primitive types to choose from - BigInt and Number. One could expect implicit conversion from "smaller" type to "bigger" type which isn't a case in JavaScript.

Expected

When computing some combination of BigInt and Number user could expect implicit cast from Number to BigInt like in below example:

const number = 16n + 32; // DOESN'T WORK
// Expected: Evaluates to 48n

Actual behavior

Expressions operating on both BigInt and Number are throwing an error:

const number = 16n + 32; 
// Throws "TypeError: Cannot mix BigInt and other types, use explicit conversions"

Why explicit conversion is needed in above cases?

Or in other words what is the reason behind this design?


回答1:


This is documented in the original BigInt proposal: 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.




回答2:


It's a design choice. In statically typed languages, coercion might give loss of information, like going from float to int the fractional part just gets truncated. JavaScript does type coercion and you may expect 16n + 32 to just use 32 as if it were a BigInt instead of a Number and there wouldn't be a problem. This was purely a design choice which is motivated here in this part of the documentation




回答3:


They are not "smaller" and "bigger". One has real but potentially imprecise numbers, the other has integral but precise ones. What do you think should be the result of 16n + 32.5? (note that type-wise, there is no difference between 32 and 32.5). Automatically converting to BigInt will lose any fractional value; automatically converting to Number will risk loss of precision, and potential overflow. The requirement for explicit conversion forces the programmer to choose which behaviour they desire, without leaving it to chance, as a potential (very likely) source of bugs.




回答4:


You probably missed an important point:
BigInt is about integers
Number is about real numbers
Implicit conversion from 32 to 32n might have sense, but implicit conversion from floating point number e.g. 1.555 to BigInt would be misleading.



来源:https://stackoverflow.com/questions/57996921/why-bigint-demand-explicit-conversion-from-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!