1

I want to parse data from an axios request on typescript

I got two interfaces

interface Department{
    code: string;
    name: string;
    country: string;
}

interface User {
    name: string;
    email: string;
    departments: Department[];
}

I got an endpoint which returns data like this

[
    {
        "name": "Estonia",
        "email": "email",
        "phone": 12345,
        "weight": "60kg",
        "country": "US",
        "departments": [
            {
              "code": 1,
              "name": "depto 1",
              "country": "US"
            },
            {
              "code": 2,
              "name": "depto 2",
              "country": "FR"
            }
        ]
        [...]
    }
]

The endpoint retrieves a lot of data which I don't need, I just want to retrieve attributes I've defined on the interface, is this possible?

I have tried this, but I got all attributes

axios.get<User[]>('http://localhost/users').then(({ data }) => {
        console.log(typeof data, data);
    });

2 Answers 2

1

The endpoint retrieves a lot of data which I don't need, I just want to retrieve attributes I've defined on the interface, is this possible?

If you use it the way you have at the moment axios.get<User[]> then you will only be able to read the properties that exist on the User interface.

The objects will have more properties but you will not be able to read / write them from TypeScript (without unsafe type assertions) so what you have is what I would do and not worry about the excess runtime properties.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Basically what I want to do is modify the properties I've defined in the interface and reply with only those. So far, I'm getting all properties. Is there another way to do this?
0

You can with tapi.js - it's a lightweight package just for this purpose.

Read the documentation here.

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.