I am facing an issue while looping through an array due to the union type. I am wondering what I have overlooked in the code below that is causing Visual Studio Code to not recognize the second optional type for that specific array.
class Menu {
// name of the menu
name: string;
// list of the ingredients in this menu
// or a list of submenu with its ingredients
list: string[] | Menu[];
hasSubList?: boolean;
}
...
menu: Menu[];
ngOnInit() {
this.loadMenu();
}
ngAfterContentInit() {
this.print();
}
loadMenu(): void {
this.menu = [
{
name: "toast"
list: [
"slide of bread",
],
},
{
name: "Crumble eggs on taste",
hasSubList: true;
list: [
{
name: "Eggs",
list: [
{
"Eggs",
"pepper",
"a pinch of salt",
}
],
},
{
name: "Toast",
list: [
"a slide of bread"
],
},
],
},
];
}
this print(): void {
for(let i=0; i<this.menu.length;i++){
let item = this.menu[i];
console.log(item.name);
for(let j=0; i<item.list.length; j++){
let list = item.list[j];
if(item.hasSubList) {
// HERE
// console intellsense says
// "property 'list' does not exist on type 'string | Menu'
// "property 'list' does not exist on type 'string'
for(let k=0; k< list.list.length; k++}(
console.log(list.list[k]);
}
} else {
console.log(list);
}
}
Recapping the message from the intellsense:
"property 'list' does not exist on type 'string | Menu'
"property 'list' does not exist on type 'string'
Why did it fail to check for Menu? Because 'list' exists as type 'Menu'