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

The NSJSONSerialization error message says, "Encountered unexpected end of file while parsing a string."

Encountering a strange issue while parsing a REST response. The problem is, it's sporadic and I can't reproduce it consistently. Sometimes it happens without any corresponding information in the error logs. Error Domain=NSCocoaErrorDomain C ...

Implementing Vue.js functionality to dynamically add or remove values from an array based on the state of a checkbox

I recently embarked on my journey to learn vue.js and I've encountered a challenging issue. I have dynamic data that I render using a 'v-for' loop. Additionally, I have an empty array where I need to store checked checkbox data and remove it ...

Error detected in JSON parsing

I keep encountering a json parse error Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 2.) This indicates that there is an issue in the jSON response. What's stra ...

Is there a way to turn off eslint's no-promise-executor-return rule?

Can the eslint rule 'no-promise-executor-return' be disabled? my .eslintrc file { "env": { "es6": true, "node": true }, "extends": [ "airbnb-base" ], "globals": { "de ...

Having trouble with obtaining precise mouseup and mousedown coordinates

Currently, I am working with react and typescript for my project. I have implemented a canvas element where I am attempting to draw a rectangle based on mouseup and mousedown events. However, the issue I am facing is that the rectangles are being drawn in ...

Angular.js: The Best Way to Attach a "Change" Event to a Service

Just starting out with angular.js... I have a HTML5 page where I can input new URLs along with names. Now, I need to validate these URLs against a back-end service to see if they already exist. How can I trigger the “onChange” event on the input field ...

Unlocking public AWS SSH keys from Vault using jsondecode

I am currently exploring the process of retrieving AWS public SSH keys from Vault using Terraform. When interacting with Vault, it seems that instead of receiving an array of strings, I am getting back a string. To handle this situation, it appears that ...

What is the methodology for obtaining the setter property type in TypeScript?

Describe a scenario where an object contains both getter and setter methods with different types. How can we determine the type of the setter function? Consider defining an object with getter and setter functions like the example below: type Foo = { g ...

When utilizing express-handlebars to render, the error message "req.next() is not a valid function

Trying to display the login page of a web application. Developed using TypeScript, node.js, express, and express-handlebars The code being executed is as follows: import exphbs = require("express-handlebars"); import cookieParser = require(&quo ...

create a fresh variable instead of appending it to the current object

I'm encountering an issue where a new array is supposed to be added on callback using props, but instead an empty variable is being added. Here's the code snippet: const [data, setData] = useState({ title: "", serviceId: "", serviceNa ...

NSJSONSerialization does not support IOS 4.3

I am working on a project that was originally designed for IOS 5. I need to update the project to run on IOS 4.3. However, when I try to run the project, I encounter two errors in the method provided below. The errors are indicated in the comments. As some ...

Divide Array of Strings in a DataFrame into separate columns

I currently have a dataframe that looks like this: df.show() +-----+ |col1 | +-----+ |[a,b]| |[c,d]| +-----+ Is there a way to transform it into the following dataframe? +----+----+ |col1|col2| +----+----+ | a| b| | c| d| +----+--- ...

Ways to add a React Router Link to a Material UI TableRow

When attempting to incorporate a Link component from React Router Dom into my Material UI TableRow, I encountered an issue. <TableRow component={Link as any} to={`/company/${company.id}`} className="clt-row" key={company.id}> The error message I re ...

"Unraveling Vue.js: A guide to fetching JSON data one object at a time

I am facing a challenge with a large JSON file (40 MB) that includes data on countries, their IDs, and a total sum that I need to calculate. { "0": { "id": 0, "country": "usa", "sum": 201, }, ...

What is the best way to extract values from a specific table column and store them in an array using Angular?

I have a section of code containing a table in my component: expect-next-month.component.html <table id="users"> <tr> <th>Number of month</th> <th>Total checking e ...

Modify the interface type whilst maintaining the structure of nested objects

In my system, I have a specific interface that outlines the structure of a NoSQL document schema. This includes strings, arrays, nested objects, and more. Here's an example representation: interface IStudentSchema { name: string; age: string; f ...

Exploring the use of data attributes in jQuery to access JSON objects

I have set a data-attribute for multiple elements and I am looking to access the JSON object using this data attribute in jQuery. <div class="content"> <div class="plans" data-plan="state-1"><span class="pricing-symbol">$</span> ...

Creating JSON from nested PHP arrays

Here's the code snippet in question: $featurecollection = ("FeatureCollection"); $test[] = array ( "type" => $featurecollection, $features[] = array($images) ); file_put_contents($cache,json_encode($test)); T ...

Efficiently Transmitting JSON Data via HTTP Requests

I have the following: Route file "prontuarios.js": module.exports = function(app){ getProntuarios = function(request, response, next){ var sqlCustom = request.query; var connection = app.infra.connectionFac ...

Decide on the chosen option within the select tag

Is there a way to pre-select an option in a combobox and have the ability to change the selection using TypeScript? I only have two options: "yes" or "no", and I would like to determine which one is selected by default. EDIT : This combobox is for allow ...