Exploring TypeScript: Understanding how to define Object types with variable properties names

Having an issue with a React + TypeScript challenge that isn't causing my app to crash, but I still want to resolve this lingering doubt! It's more of a query than a problem!

My goal is to set the property names of an object dynamically using variables. Let me illustrate with an example -> https://codepen.io/Gesma94/pen/xmwMzY

const series = {
  data: [
    {map1: "People reached", map2: 200},
    {map1: "People who called", map2: 117},
    {map1: "Contract signed", map2: 77}
  ],
  mapping: {
    stage: "map1",
    values: "map2"
  }
};

const myPar = document.getElementById("myPar");
const { stage: stageLabel, values: valuesLabel} = series.mapping;

series.data.forEach((sample: any, index: number) => {
  myPar.innerHTML = myPar.innerHTML + "<br>" + sample[stageLabel];
});

Within the forEach, I'm using sample: any.

I want to define the type of sample based on the retrieved information rather than using any. Essentially, something like:

sample: {stageLabel: string, valueLabel: number}
. However, TypeScript doesn't recognize these properties at compile time. So, I can't specify
sample: {map1: string, map2: number}
, but instead, looking for some aliasing technique.

Despite TypeScript limitations in evaluating variables, my aim is to use aliases like sample.stageLabel and sample.valueLabel where these are translated into actual properties like sample.map1 during runtime.

Hoping I've articulated my question clearly enough to grasp it.

Answer №1

Why not take the time to create a visual representation of your data?

const series = {
  data: [
    {map1: "People served", map2: 350},
    {map1: "Calls received", map2: 150},
    {map1: "Deals closed", map2: 50}
  ],
  mapping: {
    category: "map1",
    values: "map2"
  }
};    

const myParagraph = document.getElementById("myParagraph");

let mappedInfo = getMappedData(series.data, series.mapping);

// add results
mappedInfo.forEach((item:{category:string, value:number}) => {
  myParagraph.innerHTML = myParagraph.innerHTML + `<br>${item.category}: ${item.value}`;
});


function getMappedData(data, mapping): {category:string, value:number}[] {
    let categoryLabel = mapping["category"];
    let valueLabel = mapping["values"];

    return data.map(x => {        
        return { category: x[categoryLabel], value: x[valueLabel] };
    })
}
<p id="myParagraph"><b>Results:</b></p>

Please note that the compiler recognizes the type of items in mappedInfo as {category:string, value:number}, so you can exclude this information when adding and simply do:

// add results
mappedInfo.forEach(item => {
  myParagraph.innerHTML = myParagraph.innerHTML + `<br>${item.category}: ${item.value}`;
});

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

How can I pass a specific value, rather than the entire array, in a ReactJS dropdown menu?

I am facing a problem where the entire array is being passed as an argument when I call onchange after getting correct values in the dropdown. Instead of only receiving the selected value, e contains the whole array. Here is the code snippet that demonst ...

A guide on implementing RxJS Observables to target a specific DIV element

Currently, I am working with Angular 2. At the moment, I have been using this method to select a specific DIV element: <div #aaa> </div> @ViewChild('aaa') private aaa: ElementRef; ngAfterViewInit() { let item = this.aaa.nativeEle ...

Tips for efficiently exporting and handling data from a customizable table

I recently discovered an editable table feature on https://codepen.io/ashblue/pen/mCtuA While the editable table works perfectly for me, I have encountered a challenge when cloning the table and exporting its data. Below is the code snippet: // JavaScr ...

Can you explain the use of the 'this' keyword in map() and call() functions?

Recently, I've been revisiting my understanding of how to use call() and map() with a NodeList in JavaScript. It was quite easy to find information on how call() works, and there are plenty of examples of how it can be used with map(). However, whil ...

The type Observable<any> cannot be assigned to Observable<any> type

I am currently working with angular 5 and ionic 3. I have defined an interface: export interface IAny { getDataSource: Observable<any>; } Components that implement this interface must have the following method: getDataSource () { return ...

Determine the length of a string in JavaScript and PHP taking into account "invisible characters" such as and

I have a textarea where users can input text, and I want to show them how many characters they have left as they type using JavaScript or jQuery: var area = 'textarea#zoomcomment'; var c = $(area).val().length; After that, the text is validated ...

Performing an HTTP GET Request in Node.js or Express.js

Currently, I am working with express.js and require assistance in making an HTTP GET request to retrieve JSON data. Can anyone recommend some reliable node js/express js modules or libraries that can help me with performing get/post requests? ...

Executing a PHP script to initiate a ping transmission

I have a project to complete for my university involving the development of a simple application. However, I lack experience in this area and am unsure how to proceed. The objective is straightforward: I want to send ping requests to 50 IP addresses at t ...

Button-click scrolling is our featured feature!

One interesting feature on my website is a button (within a div-element) located in the bottom-right corner. I am now looking to enhance this by adding a jQuery function that enables the user to scroll down the page incrementally simply by clicking and hol ...

Is it possible to safely remove a class instance containing a GLcontext within a react.FC State to prevent memory leaks, especially when using a "class object with THREE.js"?

I have successfully developed a react.FC() application. In this application, you have the ability to throw a bottle in the metaverse (like a message in a bottle) to be discovered in the future. The app retrieves information from an API and constructs a c ...

My server keeps crashing due to an Express.js API call

I'm completely new to express.js and API calls, and I'm stuck trying to figure out why my server keeps crashing. It works fine the first time, rendering the page successfully, but then crashes with the error: TypeError: Cannot read property &apo ...

Toggle a jQuery bar based on the presence of a specific CSS class

I am working on a feature where I can select and deselect images by clicking on a delete button. When an image is selected, a bar appears at the top. If I click the same delete button again, the image should be deselected and the bar should disappear. This ...

Update the variable obtained from the user input and insert it into a new container depending on the input value

In reference to my previous inquiries, I refrain from adding more details to avoid confusion since it already received numerous responses. While I can successfully retrieve input from a text field with the ID 'test' and display it in the 'r ...

Generate a dynamic kendo dropdown with data sources assigned in separate methods

Creating a kendo dropdown list dynamically based on the number of received id's is presenting a challenge. A method has been implemented to loop through each id and generate a corresponding dropdown with that id. These dropdowns are not all generated ...

Using JSP to send variables from an external Javascript file

After creating a timer function, I am looking to display the results on a different page. The setup involves a JSP file calling functions from a separate JS file in order to output the information to another screen: Instructions in the JSP file: <butt ...

Can the lazy load script dependent on jQuery be utilized before the jquery.js script tag in the footer?

After receiving HTML from an AJAX callback, I noticed that there is a script tag for loading code that uses jQuery. However, I consistently encounter the error of jQuery being undefined. All scripts are connected before the closing </body> tag. Is ...

What is the best way to create a fixed array of unchangeable objects?

I am trying to create a class that requires an array of objects as one of its constructor parameters, with the condition that neither the array nor the objects in it can be modified. My current approach involves using the readonly modifier along with the g ...

Can the functionality of two-way data binding be achieved in Angular without utilizing ng-model and ng-bind?

During an interview, I was presented with this question which sparked my curiosity. While I have a foundational understanding of AngularJS and its ability to enable two-way data binding using ng-model and ng-bind, I am interested in exploring alternative ...

Tips for effectively eliminating errors in a redux store

Within my react-redux application, I have implemented a system to catch error responses from redux-saga. These errors are saved in the redux-store and rendered in the component. However, a major challenge arises when trying to remove these errors upon comp ...

Using vuex-class to interact with Vuex in non-Vue components

Is it possible to access Vuex outside of a Vue component using vuex-class? In a typical scenario, the process is quite straightforward: // some JS file import store from './../store'; // path to Vuex store store.commit('ux/mutationName&ap ...