Optional schema object as parse arguments to enforce BigInt vs Number #66
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This might solve the limitation
o !== JSONbig.parse(JSONbig.stringify(o))
The limitation is there because JS treat
BigInt
andNumber
as 2 separate types which cannot be cooerced. The parser decides the appropriate type based on the size of the number in JSON string. Which introduces 2 problems:- As stated above,
JSONbig.parse(JSONbig.stringify(123n))
return123
because the number is small enough- The type of one field is not consistent, for example one API can return a response in which a field can sometimes be
BigInt
and other times beNumber
There's the option to parse all
Number
asBigInt
but imho this isn't much desirable. Libraries solve problem (2) by iterating the parsed result and enforce the type as you can see here. That PR has an interesting approach which this one is inspired from.Here's the proposed solution. The parser can take a schema-like object which allow to say whether to use
BigInt
orNumber
for specific fields and parse it accordingly. This is a first prototype to show what it might look like.If this is something viable there's a lot to improve.