Q:

TypeScript Recursive function returns undefined

I have an array of Objects with the following structure:
{
  Name: "Automotive"
  RefCategory: 1,
  ChildCategories:[{
     Name: "Car"
     RefCategory: 2,
     ChildCategories: []
  },{
     Name: "Motorcycle"
     RefCategory: 3,
     ChildCategories: []
  }]
}

I wrote a function to find a Category Node given its Ref:
navigateToNode(node: any, RefCategoryToFind: number): any {

    if (node.RefCategory == RefCategoryToFind)
        return node;

    node.ChildCategories.forEach(value => {
        if (value.RefCategory == RefCategoryToFind)
            return value;
        else {
            if (value.ChildCategories.length !== 0)
                return this.navigateToNode(value, RefCategoryToFind);                
        }
    });
}

This function returns null when I call
let x = this.navigateToNode(this.activeCategories[0], 2);

I can see it hits the return value; and thus found the right node, but returns undefined.

A:

Your callback is returning a value, but the wrapping function does not return anything. Try saving the return value when it is found and return it:
navigateToNode(node: any, RefCategoryToFind: number): any {

    if (node.RefCategory == RefCategoryToFind)
        return node;

    var result;

    node.ChildCategories.forEach(value => {
        if (value.RefCategory == RefCategoryToFind) {
            result = value;
            return value;
        } else {
            if (value.ChildCategories.length !== 0)
                return this.navigateToNode(value, RefCategoryToFind);                
        }
    });
    return result;
}

