Issue
I m trying to convert an API response to typescript class/interface.
Here the API returns a list of objects with some properties, but I need only few of the properties of the response object.
API Response Example:
[{ 'Id' : 1, 'Name': 'test', 'Description: 'Test', 'PropertyX': 'x', 'PropertyY' : 'y' }, ...]
Typescript Class
Class Response { Id: string; Name: string; }
Can you please suggest me what will be the best approach for converting the JSON object to a typescript object.
Solution
I would suggest creating an interface that describes the properties you are using in your app and ignore the rest:
So assuming your response looks like:
const response = [{
'Id' : 1,
'Name': 'test',
'Description': 'Test',
'PropertyX': 'x',
'PropertyY' : 'y'
}, {
'Id' : 2,
'Name': 'test2',
'Description': 'Test2',
'PropertyX': 'x2',
'PropertyY' : 'y2'
}
];
and you are only interested in Id
and Name
, just create an interface like so:
interface IMyObject {
Id: String;
Name: String;
}
then in the rest of your app you can cast the response to IMyObject[]
For example if a function uses your response:
function myFunction(response: IMyObject[]) { ... }
or if you need to return that type, you can do a direct cast like so:
return response as MyObject[];
EDIT: As mentioned in the comment below, simply casting your object to IMyObject
does not remove the extra properties you are not interested in.
To do so, use .map
:
const formattedResponse: IMyObject = reponse.map(item => {
Id: item.Id,
Name: item.Name
});
Answered By - klugjo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.