zozourban zozourban - 1 month ago 13
TypeScript Question

Push item with interfaces on typescript

I need some help about interfaces in typescript


I have 3 interface:

export interface HomeMenu {
[name: string]: MenuItem;
}

export interface MenuItem {
title: string;
route: string;
homeMenu?: HomeMenu;
}

export interface Menu {
homeMenu: HomeMenu;
}


Now i do this :

var json: Menu = {
"homeMenu": {
"aname1": {
"title": "text",
"route": "myroute"
},
"aname2": {
"title": "text",
"route": "myroute",
"homeMenu": {
"aname21": {
"title": "text",
"route": "myroute"
},
"aname22": {
"title": "text",
"route": "myroute"
}
}
},
"aname3": {
"title": "text",
"route": "myroute"
}
}
}
json.homeMenu["aname2"].title = "myTitle";


But now how I can push a new item in the HomeMenu ? I tried to extend the HomeMenu interfaces with Array but I have an error about the index signature, Array want a number for Index(name) and not a string

I have checked the Typescript, some post and i haven't found an answer
Or maybe another solution to have a push function on homeMenu object ?
If someone can help me
Thanks in advance

Answer

How about:

json.homeMenu["aname4"] = {
    title: "title 4",
    route: "route4"
};
Comments