How to update nested properties in Typescript using bracket notation

Imagine there is an interface and object with nested properties as shown below:

interface Iobj {
  a: { a2:string };
  b: string;
}

const obj: Iobj = {
  a:{
    a2: "hello"
  }
  b: "world"
};

Now let's say we have strings that represent the properties in obj:

const prop = "a.a2"
// or
const prop = "b"

The goal is to update obj using bracket notation but encountering an error saying

Type 'string' is not assignable to type 'never'
.

obj[prop] = "newString";
obj[prop as keyof Iobj] = "newString";

It appears that obj[prop] is not recognized as valid. Is there something incorrect in my approach?

Answer №1

The issue here lies in the way JavaScript interprets obj['a.a2']. It assumes that obj should have been defined as:

obj = {
  "a.a2": "hello"
}

However, in your scenario, a2 is a child of a, so you first need to access a and then access a2. That is why using obj['a']['a2'] works for your case. If you are determined to use a.a2, you can utilize the Lodash library which recognizes this key format.

https://lodash.com/docs/4.17.15#set

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

Implementing Conditional Inclusion of Attributes in Active Model Serializer in RailsDiscover the best way to include attributes

In my Rails 4 API project, I am utilizing Active Model Serializers. I've been grappling with how to incorporate the auth_token attribute into my JSON response only when a user logs in through sessions#create. Despite referring to the AMS documentation ...

How can you show a different value in a select menu with AngularJS on selection?

When designing my menu to display US States for selection, I wanted to show both the 2-letter state code and the full name of the state initially. However, once the user selects a state, I only want to display the 2-letter code. This is how my menu looks: ...

Illustrative demonstration of Vue with TypeScript

I am currently working on developing a HelloWorld application using Vue.js and TypeScript. index.html <script data-main="app.js" src="node_modules/requirejs/require.js"></script> <div id="app">{{text}}</div> app.ts import Vue f ...

Parsing JSON data containing multiple types of objects is made simple with JSON.net

Is there a way to deserialize a list of various objects using JSON.net? string myJson = "[{action: 'a1', target: 4},{action: 'a2', targets: [1,2,3], {action:'a3', text:'targets altered'}}]"; In this scenario, we ha ...

The JSON output from the gapi (Google Analytics) array in PHP is not displaying any values

I've been utilizing the gapi class within a CodeIgniter website. The implementation I'm using is based on this resource, which returns an array that functions perfectly. To pass this array to my JavaScript, I've been attempting the following ...

Strategies for enhancing the effectiveness of a try statement when repeatedly used in Python

I am currently working on extracting various elements from a JSON object that consists of metadata related to a specific song using Python. In order to verify the availability of information, I have implemented try-except statements for each metadata eleme ...

Using JavaScript, transform a client's date/time string into a JSON-compatible date/time string

I need to find a way to convert a client's date/time string on a form into a JSON date/time string using JavaScript with moment.js for a Django REST API backend service. Here is the initial attempt: document.getElementById("dt_tm").value = moment(do ...

Having issues with adding elements to an array object in JavaScript

I've got some HTML code that looks like this: HTML: <INPUT TYPE=CHECKBOX NAME="clcik" onClick="add('1234','blah')" /> <input type="hidden" id="project" value="" /> JS: function add(obj1 , obj2){ var jsonAr ...

Error in TypeScript: The object may be null when using the window.open method

Is there a way to implement this code in Typescript? window.open(externalUrl, '_blank').focus(); Encountering the following TypeScript error: Object is possibly 'null'.ts(2531) I attempted the following solution without success: ...

Is there a way to modify the button exclusively within the div where it was pressed?

I plan to incorporate three buttons in my project (Download, Edit, and Upload). Upon clicking the Download button, a function is triggered, changing the button to Edit. Clicking the Edit button will then change it to Upload, and finally, clicking the Uplo ...

What is the best way to implement an interface for accurately checking each prop type?

Currently, while working with Typescript, I am looking for a solution to define an interface with specific properties inside my object of marks. At the moment, I am using "any", but I know there must be a better approach. Any guidance or advice on how to p ...

What is the best way to move between components within the same parent class using UI router in Angular 6?

Explore the Angular UI-Router Visualizer design.component.ts import { Component, OnInit, ChangeDetectorRef, EventEmitter, Output, Input } from '@angular/core'; import { AppService } from '@app/shared/app.service'; import { Schema } fr ...

Is it possible that the JSON-encoded output from PHP may not be valid JSON?

I have come across an interesting scenario when dealing with JSON data. The code I wrote resulted in a JSON string that had extra commas which made it invalid. Here is the code snippet: if($stmt->execute()){ $user = $stmt->get_result(); whil ...

Load JSON file into collection in server code during initialization

I recently exported a MongoDB collection to a JSON file on my local testing machine and now I'm looking to import it using Meteor.js server-side code upon startup (after deploying to a meteor.com site). Surprisingly, I haven't come across any exa ...

Tips for configuring the Index column within an Angular Mat-table (when the dataIndex displays 'NaN')

My Mat-Table is working perfectly, but I am looking for a way to add an auto-increment index. Below is the HTML code: <div class="mat-elevation-z8"> <table mat-table [dataSource]="dataSource" matSort> <ng-container matColumnDef="no"> ...

Validation messages in an Angular application using Typescript are failing to display or disappear sporadically when applied to an HTML form that has

I am currently working on a simple app that retrieves website content from a CMS [Umbraco]. After making an Ajax call, the form comes back to me as plain HTML. I then append the form to the page and use the Angular $compile service to compile the result. T ...

How can I manually listen to Angular 2 events on a dependency injected instance?

Assume I am working with a component: @Component({selector: 'todo-cmp'}) class TodoCmp { @Input() model; @Output() complete = new EventEmitter(); // TypeScript supports initializing fields onCompletedButton() { this.complete.next(); / ...

Dealing with illegal characters, such as the notorious £ symbol, in JSON data within a JQuery

I'm encountering an issue with a textarea and the handling of special symbols. Specifically, when I use $('#mytextarea').val() to retrieve text that contains '£', I end up seeing the black diamond with a question mark inside it. T ...

Is there a way to substitute the HOC with a single call and solely modify the prop?

One issue I've encountered in my project is the repetitive use of a Higher Order Component (HOC) for the header. Each time it's used, the props are set to determine whether header links should be displayed or not. My objective is to streamline th ...

Retrieving information from a data file by implementing a GraphQL Apollo Server within a NextJS application route

Currently working with Next.js 14 (app route), React, and the GraphQL Apollo framework. I have a JSON file containing data saved locally that I'd like to display using the server API. How can I make this happen? Below is the JSON structure I need to r ...