Unraveling Typescript interfaces with Axios

Looking to extract data from an axios call in TypeScript

I have defined two interfaces:

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

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

The endpoint I am working with returns data structured 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"
            }
        ]
        [...]
    }
]

Despite the large amount of data returned by the endpoint, I only want to retrieve specific attributes as specified in the interfaces. Is there a way to achieve this?

I attempted the following approach, but it retrieved all attributes:

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

Answer №1

I'm looking to only retrieve the attributes I've defined on the interface instead of all the unnecessary data. Is this achievable?

If you stick with axios.get<User[]> as you're currently doing, you'll only have access to the properties specified in the User interface.

Although the objects may contain additional properties, TypeScript won't allow you to interact with them unless you use unsafe type assertions. Therefore, I recommend sticking to your current method and not worrying about the extra runtime properties.

Answer №2

Need to accomplish this task? Look no further than tapi.js - a compact solution designed specifically for this.

For more information, check out the official documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An error occurred: The property 'toUpperCase' cannot be read of an undefined Observable in an uncaught TypeError

Encountering an issue during the development of a mobile app using the ionic framework for a movie application. After finding an example on Github, I attempted to integrate certain functions and designs into my project. The problem arises with the 'S ...

"Utilizing Ionic 3 for navigating internal links within a website using the tag

Hello everyone, I recently started exploring Ionic and Angular and I have a question regarding internal links in the Ionic framework. To begin my learning journey, I decided to work with the pre-made project called Ionic sidemenu. I am attempting to create ...

Limit file upload size to less than 1MB in Angular 2 with typescript using ng2-file-upload

Having issue with my code - I can't upload a file larger than 1mb even though maxFileSize is set to 50mb. Can anyone help me troubleshoot? @Component({ moduleId: module.id, selector: 'NeedAnalysisConsult', templateUrl: 'nee ...

Imitate a worldwide entity with Jest and Typescript

I have a React component that utilizes the global object Routes provided by the Rails gem js-routes. My component is being tested with Jest's snapshot testing feature. The issue arises when trying to mock the Routes global object in the test to return ...

Add a Filter to the Observer (__ob__) in Typescript

I am trying to implement a filter using this.Grid.option("dataSource").filter(x => x.Placeholder != null) however, it doesn't seem to be working when I run console.log(this.Grid.option("dataSource")); I receive (72) [{…}, {…}, {…}, { ...

What is the most efficient method for storing and organizing IP addresses in a MongoDB database?

I have been searching for various Q&A on ways to efficiently save and sort IPs in a mongo db, but I am struggling to find a solution. Firstly: how should I save an IP address? As a string? Integer? Something else? Secondly: Once saved (let's say ...

Exploring Different Approaches to Managing State in React Functional Components with TypeScript

Are there alternative methods of accessing and updating DOM values that are more efficient than useRef()? Should useRef() be used sparingly as the documentation recommends? import React, { useRef, useEffect } from 'react'; const Join: React.FC ...

What is the best way to extract the upcoming hours from an Array specifically containing night hours?

My task involves working with an array of hours like this: ['10:00:00', '11:00:00', '13:00:00', '14:00:00', '01:00:00']. The goal is to filter and retrieve all the hours that come after the current time. Fo ...

Options in typeahead not visible

Can someone help me with the code I'm currently working on? I successfully retrieved data from a remote service and it shows in the log, but now the typeahead feature is not displaying options when clicked. Any assistance would be appreciated. I have ...

Is query result caching implemented in the Next.js API route?

I have a Next.js application that is connected to a third-party API in order to display certain information. The data is retrieved through Next.js API routes, and the code for this can be found in /pages/api/data.js. const handler = async (req, res) => ...

What is the process for applying cdkDropList to the tbody when using mat-table instead of a traditional HTML table?

I have been experimenting with the mat-table component in my Angular project, following a simple example from the documentation: <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <!--- These columns can be ...

Attempt to create a truncated text that spans two lines, with the truncation occurring at the beginning of the text

How can I truncate text on two lines with truncation at the beginning of the text? I want it to appear like this: ... to long for this div I haven't been able to find a solution. Does anyone have any suggestions? Thanks in advance! ...

Setting the type of a prop dynamically based on another prop value

Consider the following scenario with an interface: interface Example { Component: React.ReactElement; componentProperties: typeof Example.Component; } Is there a way to determine the type of properties expected by a passed-in custom component? For ...

React function failing to utilize the latest state

I'm facing an issue with my handleKeyUp function where it doesn't seem to recognize the updated state value for playingTrackInd. Even though I update the state using setPlayingTrackInd, the function always reads playingTrackInd as -1. It's p ...

Angular progress tracker with stages

I have been exploring ways to create a progress bar with steps in Angular 12 that advances based on the percentage of progress rather than just moving directly from one step to another. This is specifically for displaying membership levels and indicating h ...

What is the best way to combine an array of objects into a single object in typescript?

Looking for some help with converting an array of objects into a single object using TypeScript. Here's the structure of the array: myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: ' ...

How come ts-jest in jest is affecting my JavaScript files?

As a newcomer to using jest with ts-jest, I am facing an error that I can't quite comprehend: $ jest FAIL src/lib/Core/Storage/JsonStorage.test.ts ● Test suite failed to run Jest encountered an unexpected token Jest failed to parse a f ...

Inference in Typescript - Detecting unknown key in an object

I am struggling to implement type inference from a props object that is passed to a component and then used in a render function. While I can retrieve the keys of the object correctly, all types are being interpreted as unknown. I need some assistance in f ...

Dynamic TenantID Recognition in Angular for Effortless Data Retrieval and Updating

I'm facing an issue in my Angular app where I have to validate the tenantId and fetch relevant data when the page is reloaded. Currently, I have scattered this logic across multiple components in my code. However, I want to streamline this process to ...

What is the reason for navigator.credentials.create returning Credential instead of PublicKeyCredential in TypeScript?

I am currently using typescript version 5.6 ("typescript": "~5.6") While trying to implement WebAuth, I noticed that the navigator.credentials.create method returns a Promise<Credential | null> https://i.sstatic.net/TMjU65xJ.png https://i.sstatic.n ...