If you copy curNode
to the TS playground, and hover over the type, you'll see its type is:
type T = {
name: string;
attributes: {};
children: never[];
}
You can't add any elements to a never[]
array.
In order to make the code work, you can declare a type and use it when you init 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:
Another option is to use new Array<any>
instead of []
when initializing the array:
const curNode = {
name: "CAMPAIGN",
attributes: {},
children: new Array<any>
};
const newNodeName = "Foo"
curNode.children?.push({
name: newNodeName,
children: []
});
console.log(curNode);