What is the process for creating a new Object based on an interface in Typescript?

I am dealing with an interface that looks like this:

interface Response {
    items: {
        productId: string;
        productName: string;
        price: number;
    }[]
}

interface APIResponse {
    items: {
        productId: string;
        productName: string;
        price: number;
        factoryId: string,
        status: number,
        category: number,
        priority: number
    }[]
}

Currently, I have a function that returns Response:

async function getList(): promise<Response> {
    // data.htw.cart.list return APIResponse
    const response = await data.htw.cart.list(postJson)
    return response
}

However, the data.htw.cart.list function returns an APIResponse, which means I receive excessive data that I do not need.

Each time I have to manually filter out unnecessary information like this:

return {
  items: response.items.map(item => {
    return {
      productId: item.productId,
      productName: item.productName,
      price: item.price
    }
  })
}

Is there a tool available that can automatically trim down the APIResponse to match the structure of Response?

Two important points to consider:

  1. The structure of APIResponse always includes that of Response
  2. The key names in Response are the same as those in APIResponse

Answer №1

To establish clear connections between your different types, it is best to define the appropriate relationships.

interface Product {
  productId: string
  productName: string
  price: number
}

interface APIProduct extends Product {
  factoryId: string,
  status: number,
  category: number,
  priority: number
}

interface ResponseData {
  products: Product[]
}

interface APIResponseData extends ResponseData {
  products: APIProduct[]
}

// Now APIResponseData can be assigned to ResponseData
let data: ResponseData = ...;
let apiData: APIResponseData = ...;
data = apiData;

// You can also assign an array of APIProducts to an array of Products, 
// but you will lose type information while keeping the fields intact
const apiProducts: APIProduct[] = [...];
const products: Product[] = apiProducts;

This approach helps the compiler understand the relationships between your types more effectively.

If you need to physically remove unnecessary fields, using the .map method as shown in your question is a good solution. Alternatively, you may consider utilizing a JavaScript library like lodash/pluck, even though this may negate the benefits of static type checking.

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

Node.js has the ability to establish internal connections, however it cannot establish connections

I'm having an issue connecting to a JavaScript file on my local server. I'd like to input the external IP address and port in order for it to run externally. This functionality currently works when accessed locally. Below is the code from my serv ...

Is it beneficial to disable and deactivate Validators in Angular?

Within our Angular framework, we've implemented a form with 10 fields. However, a new requirement has surfaced where certain individuals only require access to specific fields out of the existing 10. To accommodate this, our team is currently addressi ...

Creating React components with TypeScript: Defining components such as Foo and Foo.Bar

I have a react component defined in TypeScript and I would like to export it as an object so that I can add a new component to it. interface IFooProps { title:string } interface IBarProps { content:string } const Foo:React.FC<IFooProps> = ({ ...

Steps for converting JSON into a structured indexed array

My goal is to efficiently convert the data retrieved from my firebase database into a format suitable for use with a SectionList. I have successfully established a part of the data structure, but I am facing challenges in associating the data correctly. ...

Tips for expanding the content of a blogger page to fill the entire frame of the page

Check out this page: . Currently, the video on the page does not fill up the entire screen. Any suggestions for a solution? ...

Error in Typescript stating that the property 'children' is not found on the imported interface of type 'IntrinsicAttributes & Props'

When I try to import an interface into my Card component and extend CardProps, a yarn build (Typescript 4.5.4) displays the following error: Type error: Type '{ children: Element[]; className: string; border: true; disabled: boolean; }' is not as ...

Language translation API specifically designed to convert text content excluding any HTML formatting

I have a dilemma with translating text content in an HTML file into multiple languages based on user input. To accomplish this, I am utilizing the Microsoft Translator AJAX interface. The structure of my HTML file looks something like this; <h1>< ...

Quantities with decimal points and units can be either negative or positive

I need a specialized input field that only accepts negative or positive values with decimals, followed by predefined units stored in an array. Examples of accepted values include: var inputValue = "150px"; <---- This could be anything (from the input) ...

Stop Jade from collapsing the directory hierarchy

When it comes to implementing a build solution using NPM scripts instead of Gulp or Grunt, I have been facing some challenges in managing multiple Jade files efficiently. I've referred to resources like and for guidance. The Jade CLI allows for com ...

What is the process for including a new item in an array of objects?

const data = [ { title: 'Tasks', items: ['complete assignments', 'study for exams'], }, { title: 'Ongoing', items: ['learn new skills', 'work on projects'], }, { titl ...

Learn how to utilize JavaScript produced by the `webpack output library` in a `nodejs` application

I'm currently utilizing webpack to bundle my JavaScript into a library that serves two purposes: one for browser usage and the other for integration into Node.js applications. Below is a snippet of my webpack configuration: output: { filename: ...

Navigate to a new page on button click using Row with Tanstack / React-Table and Typescript (2339)

Encountering a linting error when attempting to navigate to a new route by clicking on a table row. The functionality is working but how can I resolve this issue? It's showing an error message stating "The property "id" for type TData does not exist." ...

Obtain an array as the response from an Ajax call

When passing data using Ajax request, I utilize the code below: var query = { "username" : $('#username').val(), "email" : $('#email').val(), } $.ajax({ type : "POST", url : "system/process_registration.php", ...

Issue with JQuery addClass functionality in Firefox

I've come across numerous posts on this topic, but none of them have provided a solution. I recently added drag and drop functionality to my website. When I drag an item over a valid container, I add a specific class to it. Here is the HTML for the ...

Press anywhere outside the container to conceal it along with the button

Utilizing an Angular directive to hide div elements when the user interacts outside of them has been effective. However, there is a specific issue that arises when clicking outside of a div on a button that toggles the visibility of the div. The 'ang ...

Setting up an Express route for updating data

I am in the process of developing a MEVN stack CRUD application (Vue, Node, Express, MongoDB). I am currently working on setting up an Express route for handling updates in my app... postRoutes.post('/update/:id', async(req, res)=> { cons ...

Grouping geoJSON data on Mapbox / Leaflet

I am currently in the process of setting up a clustered map on mapbox, similar to the example shown here: At the moment, my point data is being extracted from MYSQL and then converted into GeoJson using GeoPHP. You can view the current map setup here. I ...

How to retrieve data from an undefined table using Sequelize that is created through association

I've encountered a new challenge while working on my latest project; Imagine the tables User and Project in Sequelize have been defined. There's also a third table in the database called ProjectsUsers, and I need to retrieve data from there. T ...

Checking email existence through remote jQuery validation

Utilizing the jQuery validator plugin, I am implementing an ajax function with a remote method to validate whether an email already exists in my database. However, I am encountering an error when making the ajax call within my validation function. "email ...

Tips for implementing and utilizing an optional parameter within Vue Router

I am trying to set up a route for a specific component that can be accessed in two ways - one with a parameter and one without. I have been looking into optional parameters but haven't found much information. Here is my current route setup: { pa ...