DISCLAIMER: The following example demonstrates a potential approach, and it may not necessarily be valid or required. This approach has been personally used recently for its flexibility and adaptability.
Let's get straight to the point.
Since interfaces do not exist in runtime, if you intend to parse data effectively and apply any kind of "test" to obtain the desired information and manipulate the acquired data, utilizing classes is recommended.
Here is an illustration simulating a sample response:
const json_response = {
status: "done",
refere: {
"id": 13,
"name": "John"
}
};
In this scenario, I will implement a Response Handler that manages the entire response and a Referee
class responsible for handling the referee reference as well.
Let's start with the Referee class:
interface IReferee {
id: number,
name: string
}
class Referee implements IReferee {
public id: number;
public name: string;
private rawData: any;
constructor(data?: any) {
if (data !== null) {
// Perform necessary checks to ensure data coherence.
this.id = +data.id;
this.name = data.name;
}
}
get ID(): number {
return this.id;
}
get LowerCaseName(): string {
return this.name.toLowerCase();
}
get Name(): string {
return this.name;
}
get UpperCaseName(): string {
return this.name.toUpperCase();
}
}
The interface is optional but useful for ensuring correct implementation in the class. It also allows customization of methods as shown above.
Next, the response handler:
interface IMyJsonResponseHandler {
status: string,
refere: Referee
}
class MyJsonResponseHandler implements IMyJsonResponseHandler {
private rawData: any;
public status: string;
public refere: Referee;
constructor(data?: any) {
if (data !== null) {
this.status = data.status;
this.refere = new Referee(data.refere);
}
}
get Refere(): Referee {
return this.refere;
}
}
Similarly, thorough processing is done in the constructor based on the JSON response provided. Strict checks can be added here along with error handling. Using classes and interfaces provides easy access and understanding of properties within the JSON response.
Example usage:
const json_response = {
status: "done",
refere: {
"id": 13,
"name": "John"
}
};
let res = new MyJsonResponseHandler(json_response);
console.log(res.Refere.LowerCaseName);
You can experience intellisense benefits through the utilization of interfaces and classes together.
If your data processing requirements are complex or involve instantiating inner properties as class instances, implementing classes is preferable over just using interfaces.
Additional resources worth exploring:
How to parse JSON string in Typescript
How do I cast a JSON object to a typescript class