Currently, I am in the process of developing a program using Angular and TypeScript. Within this program, there is a specific class
named Signal
that consists of various properties:
export class Signal {
id: number;
obraId: number;
obra: string;
descripcion: string;
rangoInferior: string;
rangoSuperior: string;
unidades: string;
// additional properties
// Utilizing the ofJson method to create a Signal object
static ofJson(signalJson: ISignalJson): Signal {
return this.createSignal(signalJson.id, signalJson.obraId, signalJson.obra,
signalJson.descripcion, signalJson.rangoInferior, signalJson.rangoSuperior,
signalJson.unidades
);
}
static createSignal(id: number, obraId: number, obra: string,descripcion: string, rangoInferior: string, rangoSuperior: string,
unidades: string
): Signal {
const new_signal = new Signal();
new_signal.id = id;
new_signal.obraId = obraId;
new_signal.obra = obra;
new_signal.descripcion = descripcion;
new_signal.rangoInferior = rangoInferior;
new_signal.rangoSuperior = rangoSuperior;
new_signal.unidades = unidades;
return new_signal;
}
}
Upon receiving data from an API, certain fields (description
, rangoInferior
, rangoSuperior
) may have a value of null
which should be set to an empty string. To achieve this, private properties and getters/setters are used.
For instance:
private _descripcion: string;
public get description(): string {
return this._descripcion;
}
public set description(value: string) {
this._descripcion = value ? value : "";
}
The issue arises when the object is processed with JSON.stringify
as it includes underscore fields which can result in errors when sent back to the API.
{
"_description": "sampletext",
"id": 123456,
"obra": "TEST-PROJECT",
"obraId": 789,
"_rangoInferior": '',
"_rangoSuperior": '',
"_unidades": ''
}
Various solutions have been proposed to address this challenge:
- Implement a
toJson
method to eliminate the underscores. - Utilize
Object.defineProperties
in the following manner:Object.defineProperties( this, { _description: { writable: true, enumerable: false }, description: { get() { return this._description; }, set(value: string) { this._description = value ? value : ""; }, enumerable: true } } );
- In your opinion, what would be the most effective solution?
- Are there any alternative approaches that you believe need to be taken into consideration?