An error occurred while trying to add a property to an array because the object is not extensible: TypeError -

In my code, there is an object named curNode with the following structure:

{
    "name": "CAMPAIGN",
    "attributes": {},
    "children": []
}

I am attempting to add a new node to the object like this:

curNode!.children!.push({
        name: newNodeName,
        children: [],
});

However, I encounter the following error message:

TypeError: Cannot add property 0, object is not extensible
    at Array.push (<anonymous>)

Answer №1

When transferring curNode to the TS playground and hovering over the type, you'll find its specified type as:

type T = {
    name: string;
    attributes: {};
    children: never[];
}

No elements can be added to a never[] array.

To make the code functional, defining a type is necessary for initializing curNode:

interface TNode {
    name?: string
    attributes?: object,
    children?: TNode[]
}

const curNode : TNode = {
    name: "CAMPAIGN",
    attributes: {},
    children: []
};

const newNodeName = "Foo"

curNode.children?.push({
    name: newNodeName,
    children: []
});

console.log(curNode);

// Output
//[LOG]: {
//  "name": "CAMPAIGN",
//  "attributes": {},
//  "children": [
//    {
//      "name": "Foo",
//      "children": []
//    }
//  ]
//} 

link to TS Playground


Edit:

Alternatively, using new Array<any> instead of [] while initializing the array is another approach:

const curNode = {
    name: "CAMPAIGN",
    attributes: {},
    children: new Array<any>
};

const newNodeName = "Foo"

curNode.children?.push({
    name: newNodeName,
    children: []
});

console.log(curNode);

Answer №2

This particular post was incredibly useful in my situation.

Encountering a TypeError with Material-table: Cannot add property tableData, object is not extensible

Following VLAZ's advice, I discovered that the object was being frozen, so I took action by cloning the object using

const clonedData = structuredClone(object);

After implementing this solution, everything began to function correctly.

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

"Encountered a type error with the authorization from the credentials provider

Challenge I find myself utilizing a lone CredentialsProvider in next-auth, but grappling with the approach to managing async authorize() alongside a customized user interface. The portrayal of the user interface within types/next-auth.d.ts reads as follo ...

Unable to utilize a third setState function due to the error message indicating an excessive number of re-renders

My current challenge involves setting an initial state for my Hook. I have a clickable element that changes the state between Decreasing and Increasing upon click, and this part is functioning properly. However, I encounter an issue when attempting to defi ...

Ways to automatically close the external window upon logging out in Angular 12

I have successfully created an external window in my Angular application. Everything is working as expected, but I am facing an issue when trying to automatically close the external window upon user logout. Although I have written the code below and it wo ...

Error: The term "User" has not been previously defined

I encountered an issue while attempting to authenticate via vkontakte (vk.com) using passport-vkontakte. Error: A ReferenceError: User is not defined Below is the content of my auth.js file. var express = require('express'); var passport ...

How to implement PayPal integration in PHP

I am currently working on integrating the paypal payment system into a website dedicated to pet adoption. Initially, I had a basic code structure that was functional. However, after making some modifications and additions to the code, it no longer redirect ...

Best method for distributing components across nextjs zones?

Scenario: I am currently working on a project using Next.js and taking advantage of its multi zones feature. This feature allows us to run multiple independent NextJS applications as a unified app, managed by different teams. The Issue: One challenge I fa ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

Ways to stop touch events on every element but one through JavaScript

One issue I encountered was preventing scrolling in the background while a popover is open. For desktop, it's simple with CSS: body { overflow: hidden; } The problem arose on IOS where this rule didn't work as expected and the background could ...

Navigating to a new page once a backend function in Express has finished executing

Recently, I have been experimenting with express web servers to create a website that allows users to sign in using Discord's OAuth2 API. In order to secure sensitive information, I have been utilizing the express-session npm module to store data with ...

What is the best way to retrieve the value of a checkbox element in React.js when submitting a form?

Whenever I try to submit a form, I encounter an issue where I am unable to retrieve the value of the checked boxes (I don't mean the check value but the actual value attribute of the HTML element). Here is an example of my element in the parent compo ...

Ways to ensure text fits nicely within a container: HTML & CSS

Below is a code snippet: @import url('https://fonts.googleapis.com/css?family=Merriweather|Open+Sans'); .square { max-width: 460px; background: white; border-radius: 4px; box-shadow: 0px 5px 20px #D9DBDF; -webkit-transition: all 0. ...

Exploring Functions in Object Literal Notation in TypeScript: Why is the Context of 'this' Assigned as Type 'any'?

It appears that the question has been posed before, but my search yielded no results. The issue at hand seems rather straightforward. TypeScript integrates well with object literal notation, however, when methods are defined within, it struggles to handle ...

The React.js component search test encounters errors in locating components

I have been working on a React app that utilizes Redux and React-router. I am currently writing tests using React TestUtils, and I encountered an issue with the following test results: The first expect statement is successful: expect(nav).to.have.length(1) ...

What is the equivalent of $.fn in AngularJS when using angular.element()?

Currently, I am conducting a directive unit test using jasmine. The test is now functional, but I need to find an alternative for $.fn in angularjs since the use of $ is prohibited in my workplace. Code: (function scrollTopEventDirective(application) ...

What is the recommended sequence for adding AngularJS to the index page?

I am new to AngularJS and currently working on a project where I need to include multiple JavaScript files in my index.html page. After doing some research, I came across a post on Stack Overflow that mentioned the importance of including the angular.js fi ...

The changing of colors does not function properly when clicked in JavaScript

I am having an issue with a drop-down list that offers two options: blue and green. When I select blue and click on the text input field, its background color alternates between blue and black (the default text field color). The same applies when I choose ...

Float over a specific line in a drawing

I am looking to develop a unique rating system using css, html, and potentially js : My goal is for the user to hover over a specific section of a circular stroke and have it fill with a particular color, all while maintaining functionality. So far, I hav ...

Is there a way to bring to life the addClass() and removeClass() jQuery functions through animation?

I am currently developing a website and I want to be able to toggle the visibility of sections by using the ".hidden" bootstrap class within click events. Here is the basic code snippet: $('selector').click(function(){ $('*part-to-hi ...

Troubleshooting Rails 4: Handling a 404 Not Found Error When Making an AJAX Call to a

After spending about an hour trying to figure this out, I am still stuck... The action in my oferts_controller.rb file looks like this: def update_categories @categories = Category.children_of(Category.find(params[:categories])) respond_to ...

The react decorator for maintaining type safety fails to identify the appropriate ReturnType of the supplied function

I want to enhance the redux connect feature by using it as a decorator for a specific reducer/state. Although I know that redux connect can already be used as a decorator, I am curious about why my custom implementation does not work the way I expect. Her ...