Currently, I am immersed in a typescript project and utilizing the toJSON and fromJSON methods to effectively parse my objects.
A peculiar issue has arisen when employing JSON.stringify() on one of my classes, as it neglects to invoke the toJSON methods of the enclosed parameters.
Let me provide an overview of my classes:
class TFClass {
...
toJSON(): ITFSerialized {
console.log('not printing')
...
}
}
class ConfigClass {
transfer_functions: TFClass[];
...
toJSON(): IConfigSerialized {
return Object.assign({}, this, {
transfer_functions: this.transfer_functions,
});
}
}
Upon calling
JSON.stringify(<ConfigClass>obj)
, the transfer_functions variable is considered as TFClass[]
leading to the failure to enter the toJSON method of TFClass.
Should the transfer_functions be a singular instance of TFClass, instead of an array, then it would successfully access its respective toJSON method.
What modifications can I implement to rectify this issue?