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

Subscribe to a new Observable once the previous one completes

I need assistance in getting the current user after logging in. When I use this.router.navigate([this.returnUrl]); it does not work. Can someone please help me identify what is wrong here and how I can fix it? onSubmit(): void { this.authService.logi ...

Having trouble with AngularJS - struggling to diagnose the issue

HTML Page <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="assets/js/angular.min.js"></script> ...

Exploring the variance in outcomes when directly accessing an AuthService state versus utilizing a function in a React AuthContext

I am currently working on creating an AuthContext, but I am encountering an issue with changing the state of a variable. Here is the code snippet: index.js import Head from "next/head"; import Image from "next/image"; import styles fro ...

Methods for Addressing Absent SocketIO Session Data Within an Express Route Handler

My goal is to establish communication between Express and SocketIO on a nodejs server, allowing them to share session data. After conducting thorough research online, I discovered a potential solution at https://socket.io/docs/v3/faq/#Usage-with-express-se ...

Verify whether the element in the DOM is a checkbox

What is the method to determine whether a specific DOM element is a checkbox? Situation: In a collection of dynamically assigned textboxes and checkboxes, I am unable to differentiate between them based on their type. ...

no such file exists in the directory

My current project involves connecting a javascript file to an html file using the <script> tag. However, upon rendering the html page, I encountered an error in the console indicating that the javascript file could not be located. Here is the struc ...

Convert an array of JSON objects into a grid formatted time table using the

I am using Next.js 10 to create a timetable or schedule similar to the one below: bus stop time 1 time 2 time 3 {props[0].bus stop} {props[0].times[0]} {props[0].times[1]} {props[0].times[2]} ... {props[1].bus stop} {props[1].times[0]} {props[1] ...

Tips for updating the color, background, and height of the particle background using react-tsparticles

Is it possible to customize color and background in react-tsparticles? Below is an example of a particle configuration file named particle-config.js const particlesConfig = { background: { color: { value: "#232741", }, posi ...

Utilize JSON data to display markers on Leaflet maps

I am exploring the world of Leaflet and I have a question about loading markers from a database into a leaflet map using PHP. In my PHP code, I extract latitude and longitude data from the database based on the selected ward and encode it in JSON format. ...

Create a new array containing the keys from an array of objects

My task involves extracting the key puppies from an array of objects and returning it in a new array: The input is an array of dogs structured like this: [ {breed: 'Labrador', puppies: ['Fluffy', 'Doggo', 'Floof&ap ...

Tips for retrieving the generated ID from the server immediately following form submission using the Post method in TypeScript

When submitting a long-form, it is important to ensure that no data is lost. Users should be able to stay on the same page to make any necessary changes after clicking the submit button. I need to receive the unique id generated by the server upon submissi ...

Creating JSON with PHP: Ensuring consistent keys in JSON output derived from PHP arrays

Is there a method to convert a PHP array (or any other similar PHP object) into JSON while maintaining identical keys for a JSON array? For example: {"categories" : [ {"key": "data1"}, {"key": "data2"}, {"key": "data3" } ] } It is worth noting that the ...

Working with Node.js and MySQL can involve using callbacks within nested queries

I am trying to add data to my database only if it doesn't already exist. While attempting this, I encountered an error message: { [Error: Cannot enqueue Query after invoking quit.] code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false } My ...

Transfer data from a child component to a parent component in a React application

Currently, I am working on my second React app. This time, I am experimenting with nested components, unlike my previous project which only had a single component. The main focus of this project is a calculator app built using React. To guide my design pro ...

How does ng-repeat determine the presence of duplicates within an array of objects?

angular.module("myApp",[]) .controller("myCtrl",function($scope) { $scope.persons = [{name:"teja",age:11}, {name:"Ash",age:12}, {name:"teja",age:11}]; }); In ...

Launch Internet Explorer and input variable values (such as ScriptEngineMinorVersion)

I am looking to create a script that can open a file and inject values into it. Here is a basic example: Set WshShell = WScript.CreateObject("WScript.Shell") Return = WshShell.Run("iexplore.exe google.com", 1) However, I also need to modify some variab ...

An Unexpected Typescript Error Occurred While Creating an RxCollection With RxDB

I'm new to RxDB and I've come across a strange Typescript error in my Electron project. Here are the relevant parts of my code: import RxDB, { RxCollection, RxDatabase } from "rxdb"; RxDB.plugin(require("pouchdb-adapter-idb") ...

Showing a DIV multiple times with an additional text field in HTML and JS

As someone new to development, I am facing a requirement where I need to create a form with a dynamic field that can be added or removed using buttons. When the user clicks on the Add button, another field should appear, and when they click on Remove, the ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

Mastering the correct application of both Express's res.render() and res.redirect()

After implementing a res.redirect('page.ejs');, my browser is displaying the following message: Cannot GET /page.ejs In my routes file, I have not included the following code structure: app.get('/page', function(req, res) { ...