Converting types in Typescript by utilizing destructuring rest on deeply nested objects

// initial types
 interface Source {
  id: string;
  version: number; // discard
  masterVariant: MasterVariant;
}

interface MasterVariant {
  id: number; // discard
  sku?: string;
}


// updated "simplified" types
 interface Target {
  id: string;
  masterVariant: MasterVariantLight;
}

interface MasterVariantLight {
  sku?: string;
}

To eliminate the version property, you can implement the following:

export class Convert {
    public static toTarget(source: Source): Target {
      const { version, ...result } = source;  
      return result;
    }
  }

If you are looking to remove masterVariant.id using the same transformation method, do you see any possibilities?

Answer №1

public class Converter {
  static changeFormat(inputData: Data): FormattedData {
    const { version, mainItem: { id, ...otherProps }, ...rest } = inputData;
    return { id: rest.id, mainItem: { ...otherProps } };
  }
}

Playground

Answer №2

Although one could opt for pure destructuring in this scenario, I believe it would be more straightforward to add another line to format the necessary `masterVariant` object.

Furthermore, having a class that remains uninstantiated serves little purpose - a simple function would be more appropriate for this task (which is perfectly acceptable, unlike in the realm of Java).

const convertSource = (inputSource: Source) => {
    const { masterVariant, ...remainingSource } = inputSource;
    const updatedMasterVariant = { sku: masterVariant.sku };
    return { ...remainingSource, masterVariant: updatedMasterVariant };
};

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

Dynamically binding image URLs in VUEJS

Below is the JSON data containing button names and their corresponding image URLs: buttonDetails= [ { "name": "button1", "images": [{ "url": "https://localhost:8080/asset/d304904a-1bbd-11e6-90b9-55ea1f18bb ...

Alternating row colors using CSS zebra striping after parsing XML with jQuery

After successfully parsing XML data into a table, I encountered an issue with applying zebra stripe styling to the additional rows created through jQuery. Despite my efforts to troubleshoot the problem in my code, I remain perplexed. Below is a snippet of ...

The for each loop fails to return the value

In my Vue component, I have a conditional loop that iterates through train stations with 'New York' as the destination or on the route. <tr v-for="departure in filterTrainStations" :key="departure.name"> <td>{{ departure. ...

Ways to Share Multiple Table Checkboxes

As someone new to development, I encountered the following issue. https://i.sstatic.net/D8EIb.png In the image above, you can see that I have a pagename and three Radio buttons - view, edit, and update. Here is my code: <td>{{product name}} < ...

The responsive menu refuses to appear

my code is located below Link to my CodePen project I'm specifically focusing on the mobile view of the website. Please resize your screen until you see the layout that I'm referring to. I suspect there might be an issue with my JavaScript cod ...

Issue: Ajax is not defined

When attempting to call a URL in the background using the following code within a script tag: var request = new Ajax.Request(logoffURL, {method : 'post'}); I encountered a script error stating Ajax is undefined. Is it necessary to include any ...

Defining the NgRx root state key within the application state interface

Here is an example of a selector taken from the NgRx documentation: import { createSelector } from '@ngrx/store'; export interface FeatureState { counter: number; } export interface AppState { feature: FeatureState; } export const sel ...

The art of combining TypeScript recursive functions

Looking to establish a function chain input for a pipe/flow/compose function. Is it feasible without directly expanding the types to a certain depth, contrary to common practice? Check out lodash's flow. The goal is to enforce data flow type checkin ...

What is the reason behind these sinon stubs returning undefined values?

I have created a unit test for this code snippet and used Sinon to stub the browser methods (specifically with sinon-chrome, an older but still functional library that suits my needs). /** * Returns an array of languages based on getAcceptLanguages and ge ...

What could be the reason for the malfunction of the Bootstrap panel toggle feature in a ReactJS production build

In my ReactJS development, I have successfully added Bootstrap panel toggle functionality. However, I encountered an issue when deploying the React build code - the panel is not expanding. After investigating, I realized that the problem lies in using hr ...

Disabling caching for Twitter Bootstrap modal

Check out this demo I created to test Bootstrap modal and JSON parsing. View the code here Clicking the "show" button loads JSON data, parses it, and displays it in a modal. However, the issue arises when clicking "show" again as the previous list is no ...

Building an instance using an object and an array with Vue.js 2.0

I am working with an array and an object created in Vue.js, and my goal is to combine them into a single 'selection' array following this format: selection[ {food: Chicken, quantity: 3}, {food: Rice, quantity: 2}, {food: Pasta, quantity: 1} ]; ...

Encountering Rollup errors while creating a Vue 3 application using Vite and deploying it on Vercel

As I try to build my Vue 3 application using Vite and deploy it on Vercel, I am encountering an error. While the application works perfectly in the development environment, I am facing issues during the build process. The error message that pops up is: Ro ...

verifying the presence of a specific key within a dictionary in Python

Check out the javascript code snippet: const isValid = function (area, row, col, num) { if (area[num] || row[num] || col[num]) { return false; } else { return true; } }; I attempted to convert this into python but encountered some difficulti ...

Error: The 'price' property is undefined and cannot be read at path C:NODEJS-COMPLETE-GUIDEcontrollersshop.js on line 45, character 37

I have been attempting to add my products to the cart and calculate the totalPrice, but I keep encountering an error. Here is the error message:- enter image description here. Below is the code from my shop.js file:- exports.postCart = (req, res, next) =&g ...

Guidelines for attaching a div to the bottom of a page?

I have a navigation menu inside div.wrapper, and I am trying to make the div.wrapper stick to the footer. <div class="wrapper"> <div id="menu"> <ul> <li>1.</li> <li>2.</li> ...

Seeking guidance on utilizing JavaScript for implementing an onclick event

I am exploring the realm of Event tracking with Google Analytics. To make this happen, I know that I must include an onclick attribute to select links (those specifically requested for tracking) in the following manner: <a href="http://www.example.com" ...

Learn how to use @ngx-translate to translate text in .ts files within an Angular

Currently, I am tackling a meteor-Angular project where I am utilizing @ngx-translate for the purpose of translation. In terms of HTML files, the translation is seamless and functions perfectly using a JSON file for translation. However, when it comes to ...

Help! I'm receiving a modal error message requesting an ID for the correct modal view. How can

Here's the code snippet I've been working on: <!DOCTYPE HTML> <html> <head> <title> EURO CATALOGO </title> <style> #myImg { border-radius: 5px; cursor: pointer; transition: 0.3s; } #myImg:hove ...

Encountering a 405 HTTP error in Angular8 app when refreshing the page

Currently, I am working on a project using Angular8 and .NET Core 3.0 in Visual Studio. Everything is running smoothly except for one issue that arises when I press F5 on a page with a form. The error message that pops up reads: Failed to load resource: ...