Typescript restricts dynamic property access within objects

I'm encountering some difficulties while attempting to access my object property in TypeScript:

const sum = (type: string) => {
  return {
    status: 'Sum',
    value: data?[type].sum,
  };
};

sum('first')

Here is a glimpse of my data structure:

data: {
  first: {
    sum: 15
  },
  second: {
    sum: 515
  }
}

Upon trying to access the property, I am presented with

TS2339: Property 'sum' does not exist on type 'string[]'.
Why is this happening and what is the solution to this issue?

Answer №1

If you are in need of the optional chaining operator, then the correct syntax to use is data?.[type].

It is important to note that TypeScript will generate an error if you attempt to access an object field using object[property] without providing specific types. The code snippet below illustrates this point:

interface Data {
  first: {
    total: number
  },
  second: {
    total: number
  }
}

const data: Data = {
  first: {
    total: 15
  },
  second: {
    total: 515
  }
}

const total = (type: keyof Data) => {
  return {
    status: 'Total',
    test: data?.[type].total
  }
}

total('first')

For a working example, check out this live demo.

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

Internet Explorer 11 XHR Troubles

Our company has successfully developed a JavaScript video player that can be embedded on various websites using a script tag. As part of the bootstrapping process, we utilize XMLHttpRequest to fetch resources from our server. This creates cross-origin requ ...

Error: Access Denied - discord.js bot command cannot be executed due to lack of authorization

Every time I initiate the bot and try to execute my "ping" command, an error occurs: js:350 throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError: Missing Access at RequestHandler.execute (C: ...

How To Access a View by Clicking in Ionic Framework

I have designed the main screen shown below. When each link is clicked, it should open the corresponding view. https://i.sstatic.net/H84jt.png Here is what I have created so far: Main Screen <body ng-app="starter"> <ion-pane> < ...

One-click process succeeds where two clicks fail

The code below is intended to go through a two-click process as follows: First click on .imagenes decreases opacity and makes .logo visible. Second click on .imagenes returns the opacity to 1 and hides .logo again. However, during this cycle of two ...

Refining an array data table within a nested component

Transitioning my old PHP/jquery single-page applications to VueJS/Webpack has been a journey I'm undertaking to familiarize myself with the latter technology. It involves converting a simple table that pulls data from a JSON API and incorporates filte ...

Angular 11 is indicating that the type 'File | null' cannot be assigned to the type 'File'

Hey there, I'm currently diving into Angular and I'm working on an Angular 11 project. My task involves uploading a CSV file, extracting the records on the client side, and saving them in a database through ASP.NET Web API. I followed a tutorial ...

What is the best way to access the display property of a DOM element?

<html> <style type="text/css"> a { display: none; } </style> <body> <p id="p"> a paragraph </p> <a href="http://www.google.com" id="a">google</a> &l ...

Updating model/schema dynamically within Express Router

My express server handles api calls by directing them to specific routes. app.use('/api/data01', require('./routes/dataRoute01')) app.use('/api/data02', require('./routes/dataRoute02')) app.use('/api/data03&apo ...

Choose a selection from the options provided

This is a sample for demonstration purposes. I am trying to display an alert with the message "HI" when I click on Reports using the id main_menu_reports. My attempted solution is shown below. <ul class="nav" id='main_root_menu'> & ...

Enhance your cloud functions by updating data

Recently, I encountered an issue with a function I wrote that interacts with the Real Time Database. Every time I attempted to write data to a specific node, it would add the complete dataset and then promptly delete everything except one entry. https://i ...

The name field in the request body is currently undefined

Currently, I am working on developing a basic blog page using technologies such as ejs, JavaScript, Node.js, Express, and body-parser. While working on passing inputs to the command line, specifically for the title, I encountered an issue. When I used req ...

Angular Tutorial: Modifying the CSS transform property of HTML elements within a component directly

Currently, I'm in the process of developing an analog clock for a project using Angular. My challenge is figuring out how to dynamically update the sec/min/hour handlers on the clock based on the current time by manipulating the style.transform prope ...

Is there a way to extract JSON keys that begin with a numerical value?

I am attempting to retrieve JSON data from sparkfun using ajax: var token = "someToken"; var jsonData = $.ajax({ url: "https://data.sparkfun.com/output/" + token + ".json", data: { page: 1 }, dataType: "jsonp", }).done(function (results) { ...

Creating a List programatically in material-ui can be easily achieved by following these steps

I am attempting to create a contact view using the list component from Material-UI. My code is written in typescript, but I am struggling with setting up react and material-ui correctly. Any guidance would be greatly appreciated. export interface IConta ...

Tips on securely passing dates in JavaScript without leaving them vulnerable to manipulation

The date and time stored in my database appear to be manipulated when fetched. Specifically, when I send this data directly via email from the server, the date and time change. When accessing the date on the client side, it appears as expected. However, i ...

Validating phone numbers in Saudi Arabia for both mobile and landlines

I've been struggling to validate a Saudi Arabia phone number on my Bootstrap form, but I keep running into an invalid error. Here is the current regex pattern I am using: /^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/ function ch ...

A guide to simulating ngControl in a Custom Form Control for effective unit testing in Angular

I need some guidance on creating unit tests for a Custom Form Control in Angular 9. The issue arises with this line of code: constructor(@Self() private ngControl: NgControl), which triggers an error: Error: NodeInjector: NOT_FOUND [NgControl]. It seems th ...

Tips for removing duplicate objects from an array

I am utilizing the underscore.js plugin in my code I experimented with it on jsfiddle var basket=[{ "basketitems":[{"items":[]}], "itemdetails":[{ "amountPledged": "100", "bActivity": "Handloom Wo ...

What is the best way to arrange buttons in a row horizontally?

Desired Output I need help aligning the buttons as shown in the Desired Output image, but when I run the code, the buttons stack vertically, resulting in Output like this. I've included the HTML, CSS, and JS code below. As a beginner in UI design, I ...

Do we need a peer dependency specifically for TypeScript typings or is it optional?

My TypeScript library includes a React component, and one of the optional features allows users to pass an instance of a Redux store as a prop for Redux integration. <Component reduxStore={store}></Component> Since this feature is optional, I ...