I have a wrapper class in TS that accepts a string in constructor and converts into a bigint internally. I want to customize the serialization/deserialization of this class's object,
export class MyInt64 implements MyDataTypes {
private readonly _internal: BigInt;
constructor(val: string) {
this._internal = BigInt(val);
}
toJSON() {
return {
val: this._internal,
};
}
}
when JSON.stringify(new MyInt64("9223372036854775807")) gets called I want it to not round the number down to 9223372036854776000.
How to do this?
Edit
For my type MyInt64 I want the JSON.stringify() yield into string and that I can do it by overriding toJSON() and keeping track of an internal string variable.
However I want to do MyJSON.stringify() which wraps JSON.stringify() and converts the string value of MyInt64 to number.
Clarification
export interface IUser {
id: MyInt64;
name: string;
balance: number;
}
const user : IUser = {
id: new MyInt64("9223372036854775807"),
name: "Alice",
balance: 123
};
// normal framework serialization & deserialization
const userString1 = JSON.stringify(user);
// This is expected to be {"id":"9223372036854775807","name":"Alice","balance":123}
const userStringCustom = JSON.stringify(user, (k, v) => {
if (value instanceof MyInt64) {
// call JSONBig.stringify(value) using json-bingint lib
}
});
// This is expected to be {"id":9223372036854775807,"name":"Alice","balance":123}