Using the syntax ['] to access dynamic properties in Typescript

class Bar{
 dynamicProperty: string;
}

I am curious about the behavior when accessing dynamic object properties. I came across an interesting approach in one of the answers provided here:

let barObj: Bar = someObj['dynamicProperty']; 

However, attempting to access the property directly like this results in an error.

let barObj: Bar = someObj.dynamicProperty;

I want to delve deeper into why the first method is successful in handling dynamic objects.

Error message displayed:

"dynamicProperty does not exist on type"

The question was previously discussed, and Angelo R's response caught my attention.

Original Question Link

Answer №1

In TypeScript, there is a helpful convention that allows you to access properties not explicitly defined in an object's type signature. By using the ["bar"] notation, you can easily retrieve any arbitrary property without the type checker enforcing its presence in the type signature of the object.

Answer №2

My preferred method for accessing object properties is by using

const myproperty = 'name' as const;

type MyObject = {
        name: string,
        age: number;
    }

    let obj:MyObject = {name: 'Ryu', age:30};
    const myproperty = 'name' as const;
    
    console.log(obj[myproperty])

For instance, if you need to calculate the sum of the 'visited' property in a function called sum(), and then later calculate the sum of 'deals' using the same function, you can store all properties in an array and pass the index of this array as an argument to sum(0) or sum(1).

type Sale = {
    id: number;
    visited: number;
    deals: number;
    amount: number;
 }

let data:Array<Sale> =[{id: 1, visited: 83, deals: 66, amount: 5501},
{id: 2, visited: 113, deals: 78, amount: 8290},
{id: 3, visited: 36, deals: 12, amount: 6096}]

const args = ['visited',  'deals', 'amount'] as const;

 const sum = (property:number) => {

        let total:number = 0;
        data.forEach((element) => {
            
            total += element[args[property]];
        });
        
        return total;
    }
    
console.log(sum(0))  //Visited  
console.log(sum(1))  //deals
console.log(sum(2))  //amount

Alternatively, you could utilize enum for a more universal approach.

 enum CategoryOfSum{
        VISITED = 'visited',
        DEDALS = 'deals',
        AMOUNT = 'amount'
    }
    
    const sum = (type:CategoryOfSum) => {

        let total:number = 0;
        data.forEach((element) => {
            
            total += element[type];
        });
        
        return total;
    }

sum(CategoryOfSum.VISITED)
sum(CategoryOfSum.DEDALS)
sum(CategoryOfSum.AMOUNT)    

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

Guide on properly specifying mapDispatchToProps in a component's props interface

In my project, I have a connected component utilizing mapStateToProps and mapDispatchToProps along with the connect HOC from react-redux. My goal is to create concise and future-proof type definitions for this component. When it comes to defining types fo ...

Creating a loop to dynamically generate HTML input elements for ProcessingJS

Utilizing HTML input fields to manipulate a sketch, I am now aiming to create a loop to produce multiple inputs. var uivars = { tA: "40", // defining initial values tB: "10", }; Subsequently referencing those variables in the sketch: <script type ...

The method defined in the external script for React is not recognized

For my React project, I am trying to import BlotterJS. In order to do so, I have added the following script in my index.html file: <script crossorigin src="https://rawgit.com/bradley/Blotter/master/build/blotter.min.js"></script> Wit ...

The functionality of JQuery keyup and keydown events seems to be malfunctioning specifically in the Chrome

$('#user_text').keyup(function(){ var user_text = $('#user_text').val(); $('#user_text_feedback').html(user_text); }); <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title&g ...

Twists and turns as I mix up Kineticjs

After scrambling my puzzle, I now need it to be rotated. Can anyone help me with this? Thanks :) fillPatternImage:imageObj, x:-pieceWidth*i/2, y:-pieceHeight*j/2, stroke: "#000000", ...

Display the files contained within a folder on the right side of a container by utilizing vue.js

I am currently working on an application that involves a list of folders, each containing various files. The goal is to display these files when a specific folder is chosen. On the left side, users will see a list of folders and on the right side, the resp ...

conceal the mustard-colored dots within the overlay

Whenever I trigger the link, a modal window pops up, but it comes with an unwanted black background color and yellow dots. How can I prevent the yellow dots from showing up on the overlay? http://jsfiddle.net/y88WX/18/embedded/result/ <nav class="da-d ...

unable to properly assess the functionality of the timeout feature within the useEffect hook

I've been working on a lazyload image loader component that only loads images if they have been visible for more than 500ms. Although the functionality is working as expected, I'm facing challenges when it comes to writing a test to validate its ...

Utilize a function as a parameter

I am struggling to figure out how to make this function pass by reference in my code. Is there a way to achieve this? var Class = function() { var callback1; var callback2; function buildStuff(data, callback) { element.onclick = funct ...

The Express.js static() function seems to have trouble serving files from subdirectories that are more than one level deep

My Express.js app has a folder structure displayed on the left. Line 19 utilizes static(). The path for './client' is defined, with path.join() included as well. In the network log on the right, all assets load properly except for the components ...

Implementing a Countdown Clock in Auction Listings

Similar Question: Countdown to a specific date Is there a way to implement a jQuery countdown timer that starts from the day of posting an advertisement and ends on the expiry date? ...

Is it possible to create a website with a single session for all users using JavaScript

Greetings everyone, I am excited to be posting for the first time on stackoverflow. After dedicating a week to learning javascript and achieving some things I am proud of, I have hit a roadblock. As a self-learner, I kindly ask for your understanding. Cur ...

Ways to prevent an array from being reset

My issue involves the clothes and orders tables, along with an array based on Clothes and Orders models. Whenever I add a clothes element into the Orders array and specifically update the amount and price of the selected item, it also updates the Clothes a ...

Evaluating the generated HTML using JavaScript and Selenium testing

I am a new user of Selenium using C# and I want to automate the login process on a third-party website. When I manually navigate to the page in Chrome and inspect the elements, I can see the text boxes for username and password. <input type="text" id=" ...

Attempting to incorporate a variable into the URL while making an Ajax POST request using jQuery

Currently, I am attempting to create a post using jQuery.ajax instead of an html form. Below is the code I am using: $.ajax({ type: 'POST', // GET is also an option if preferred url: '/groups/dissolve/$org_ID', data: data, success: fu ...

Retrieve the IDs of list elements in order to dynamically update a div using AJAX

I'm facing a bit of a challenge at the moment. I have a webpage that uses jQuery to load three different views: one displaying all categories associated with the user, another showing the image and name of items within the selected category, and a thi ...

Issue with Vue JS component on blade template page

Having trouble loading a Vue component into a Laravel blade file? Despite making changes, the content of my vue file isn't showing up in the blade file - even though there are no errors in the console. Any suggestions on how to resolve this issue woul ...

Customize CSS based on user's device in Google Script Web App

Seeking Clarity: I have a straightforward project involving a Google Script / Web App, but I am struggling to find a way to load a specific CSS file based on the user's device. In other words, rather than focusing on responsive design, I need to loa ...

The height of iScroll4 becomes incorrect following the submission of an AJAX form. The height reverts back to its original value before

I have integrated a form within an iScroll4 scroller. The form is an ajax form created using the Gravity Forms plugin in WordPress. After submitting the form, I noticed that the height of the iScroll remains the same as it was generated on page load. This ...

The find function is malfunctioning in React

My goal is to have my code send specific username strings to the Profile page using the username props retrieved through the find() method and store the result in a function named user. However, I'm facing an issue where the find method doesn't c ...