9

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.

1
  • 1
    Don't want to add another answer, as both possibilities are already mentioned. The best way is to iterate through your response and create new objects according to your class and return them. You should not cast the result, as this is only a way to trick the TypeScript compiler and can lead to weird problems. Commented Apr 30, 2018 at 8:32

2 Answers 2

9

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
});
Sign up to request clarification or add additional context in comments.

2 Comments

this is definitely not the way to go. This may work as a hack but that is not how it is supposed to work. Because your objects will still contain the other properties, just for TypeScript they are invisible. Imagine sending this object to an API because you think only Id and Name in it but you actually send more data. Casting DOES NOT remove or change any properties. I highly recommend to not use this approach
Edited my answer to reflect your comment, which I agree with. Cheers
2

You can use forEach method and create a new object with the properties you require.

myarray=[];
 ngOnInit() {
     this.myvalues();

  }


    myMethod()
        {
           const response = [{
            'Id' : 1,
            'Name': 'test',
            'Description': 'Test',
            'PropertyX': 'x',
            'PropertyY' : 'y'
          }, {
            'Id' : 2,
            'Name': 'test2',
            'Description': 'Test2',
            'PropertyX': 'x2',
            'PropertyY' : 'y2'
          }
        ];

        response.forEach(value=>{
         this.myarray.push(
               {
                'ID':value.Id,
               'Name':value.Name
              }
            )
        });
        console.log(this.myarray);

WORKING DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.