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);