To achieve this task, you have various options available but one crucial aspect to address is correcting the data types as they are currently inaccurate. Additionally, manual transformation of your result object is required.
Currently, the data types indicate that Axios.get
will provide a model with keys named Id
and Name
, which is incorrect since it should actually return a model with keys named id
and name
. While you can convert the result accordingly, it is essential to rectify the initial return value information.
Once the data types are corrected, you can proceed to transform the JSON response into the desired model format. One approach is utilizing lodash, which simplifies this conversion process.
An illustrative example could be structured as follows:
export type Model = {
Id: number,
Name: string
}
// Obtain the raw response adhering to the accurate response type
const response = await Axios.get<{ id: number, name: string }>(source);
// Convert it into a new object aligning with the desired type
const model: Model = _.mapKeys(response,
(value, key) => _.upperFirst(key) // Converting camelCase keys to PascalCase
);
Keep in mind that there are numerous alternatives for the final transformation step. The above example serves as just one potential solution. It may also be beneficial to consider implementing validation initially to ensure the response data conforms to your expectations, especially if there is a risk scenario involved.