What are some techniques for breaking down or streamlining typescript code structures?

Within my TypeScript class, I have a skip function. In the interface, I've specified that the data is coming from the backend.

Now, on the frontend, I want to be able to rename the backend variables as demonstrated below. There are multiple variables and I'm seeking ways to optimize the code efficiently.

I contemplated using the Destructuring concept but I'm uncertain about how to implement it. Any assistance would be greatly appreciated.

this.recordId = data?.data1;
   this.oldValue = data?.data2;
    this.newValue = data?.data3;
     ............// many more

The TypeScript function:

skip(rec: ABC) {
  const { data1, data2, data3 } = rec;

  this.records.skip({ data1, data2, data3}).subscribe(data => {
    this.recordId = data?.data1;         
    this.oldValue = data?.data2;        
    this.newValue = data?.data3;        
     ............// many more

    this.processIncomingRecord(data);
  });
}

rec.ts

export interface ABC {
    data1: number;
    data2: number;
    data3: number;
}

Answer №1

To enhance your code structure, consider implementing a secondary "helper" map object named MapABCToDEF. This map will correlate keys from ABC to their corresponding frontend key names in a new type called DEF, utilizing the "mapped types" feature introduced in TS 4.1 and above.

interface ABC {
    data1: number;
    data2: number;
    data3: number;
}

const MapABCToDEF: {[Property in keyof ABC]: string} = {
    data1: 'recordId',
    data2: 'oldValue',
    data3: 'newValue'
}

type DEF = {
    [Property in keyof typeof MapABCToDEF as typeof MapABCToDEF[Property]]: ABC[Property];
}

This approach ensures better type information flow where needed. It's advisable to maintain consistency in naming conventions between the frontend and backend data structures. Trying to match the names like using data1 on the backend and recordId on the frontend can introduce complexity and confusion. Standardizing the naming convention across both ends is recommended for smoother development.

For simplifying the renaming process, leverage the MapABCToDEF map object to dynamically assign key-value pairs to this with type enforcement:

const abc: ABC = {
    data1: 100,
    data2: 200,
    data3: 300
}

// ...

const keys = Object.keys(abc) as Array<keyof typeof abc>;
keys.forEach(eaKey => {
    this[MapABCToDEF[eaKey]] = abc[eaKey];
});

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

Modifying a Component's Value in its Template Based on an IF Condition in Angular 6

How can I display or hide the 'separator-container' based on a specific condition in the row data? The condition to satisfy is mentioned as "myConditionCheck" in the 5th line of code. I attempted to achieve this by using "isWarningSeperatorVisib ...

The Autocomplete field's label remains visible even after the form is submitted

I am currently developing a feature that allows users to select an option in the Autocomplete component. In the parent component, I pass these props: const filterDropdownConfig: FilterSelectAutocomplete = { data: scenariosList, label: { className: &apos ...

Issue encountered while loading ng2-bootstrap

Encountering an issue with importing ng2-bootstrap. Here is the error message: http://localhost:3002/ng2-bootstrap/ng2-bootstrap.js 404 (Not Found) Error: Error: XHR error (404 Not Found) loading http://localhost:3002/ng2-bootstrap/ng2-bootstrap.js at ...

"Encountering a 400 bad request error when making a Graphql POST

Seeking assistance with my graphql code. I have included the service and component files below. I am currently new to graphql and not utilizing the apollo client; instead, I am attaching a query on top of the HTTP POST call to send requests to the graphql ...

What is the best way to send a variable to an event listener?

Forgive me if my issue seems insignificant to those well-versed in JS. I've developed an image carousel and am working on linking a thumbnail to a full-size image, so that when a user clicks on the thumbnail, the larger image appears in another sectio ...

Is there a way to export all images that have been imported into a React JS file with just one export command?

In the process of developing a solitaire game using React, I have implemented a Card component that displays a card on the screen based on its suit and number. Inside the Card.js file, there are several imports for image sources, such as: import cardFrontT ...

404 Error message encountered across all routes in a Node TypeScript Azure Function App - Resource not located

I keep encountering a 404 Not Found error on all routes while requesting my API. I am struggling to correctly write the code. Here's an example of my code: host.json: { "version": "2.0", "extensions": { & ...

What steps can you take to resolve the "TypeError: Cannot read property 'id' of undefined" issue?

I have been developing an app that involves using databases to add items for users based on their user ID, which is their username. However, whenever I attempt to add an item, I encounter an error that I can't seem to troubleshoot. The error message r ...

I am able to view the node-express server response, but unfortunately I am unable to effectively utilize it within my Angular2 promise

https://i.stack.imgur.com/d3Kqu.jpghttps://i.stack.imgur.com/XMtPr.jpgAfter receiving the object from the server response, I can view it in the network tab of Google Chrome Dev Tools. module.exports = (req, res) => { var obj = { name: "Thabo", ...

The final condition of the ternary operator fails to render if the specified condition is satisfied

Having trouble identifying the issue with this ternary statement. The last element (blurredscreen) is not appearing when authStatus !== "authenticated". return ( <> <div key={"key-" + id}> {isO ...

Why is a dispatch call in React-Redux being executed before another?

My Pokedex is functioning properly, but I have encountered an issue with React-Redux Dev Tools: The function "getPokemonsInfo" is being called before "getPokemonsUrls", however, "getPokemonsInfo" should only be triggered when a property in the state chang ...

Tips for adding styling to HTML in Vue by entering CSS code into the CodeMirror editor

Is there a way to style HTML by entering CSS code into the Codemirror editor? For instance, if we have the HTML code <head> </head>, how can I apply the CSS code, head{ color : red }, typed in the Codemirror editor to stylize this HTML code? mo ...

Developing a user-friendly widget for a website that is not optimized for mobile devices

Here's the backstory: I'm currently in the process of creating a mobile-friendly widget for my clients. Unfortunately, they have web pages that are not optimized for mobile devices, and it doesn't seem like that will change anytime soon. Th ...

Using ng-if in AngularJS to compare two objects

I am transferring between controllers with different formations, and I am attempting to use "ng if" to compare the ids, but it is not functioning as expected. Below is the code snippet: var postsApi = 'http://mywebsite.com/wp-json/posts?filter[p ...

Strange CSS/browser storage glitch

UPDATE: JUST REALIZED THIS ISSUE IS ONLY OCCURRING ON FIREFOX, NOT CHROME ANOTHER UPDATE: Oddly enough, this problem only occurs locally. When I push it to GitHub, everything works fine. So strange. I suppose that means it's not a major issue. On my ...

Error 414: The URL exceeds the maximum length and cannot be processed

I am currently utilizing vuejs and sending an axios request to the server in order to download a csv file. download() { var that = this //this.records = [{id: 1, name: 'Jack'}, {id: 2, name: 'Jacky'}, {id: 3, name: &apos ...

Difficulty encountered while implementing mouseover event listener for an SVG component

I'm having trouble triggering an event for an svg element. Here's the link to my jsfiddle example: https://jsfiddle.net/r1ahq5sa/ Here's the HTML code: <div class="row"> <div class="col-md-8"> <svg class="video-nav-bar ...

Having trouble with Semantic UI Modal onShow / onVisible functionality?

Seeking assistance with resizing an embedded google map in a Semantic UI modal after it is shown. After numerous attempts, I have narrowed down the issue to receiving callbacks when the modal becomes visible. Unfortunately, the onShow or onVisible functio ...

What is the term for specifying a variable's data type using a set of values instead of a traditional type?

Recently, I stumbled upon some code that introduces a class with specific variables defined in an unconventional manner. export class Foo { id: string = "A regular string" bar: '>' | '<' | '=' | '<=' | ...

How to deactivate an option in md-autocomplete

I encountered a scenario where I converted an md-input-container with a md-select/md-option to a md-autocomplete. While in the initial setup of md-select/md-option, we were able to apply ng-disabled property to both the md-select and md-option. However, wh ...