Mohammad Osama
Mohammad Osama

Reputation: 59

Check if object's attributes exist throws compile errors

How do I have some code only run in Angular 4 (TypeScript) when an object's attribute exists? I've tried this code:

navigation.forEach(function(x, k) {
            if('children' in x){
                x.children.forEach(function(data, key){
                //console.log(data);
                if(data.url){
                    let value = data.url.indexOf(url) !== -1;
                    if(value){
                        navID = data;
                        //console.log(value);
                    }
                }else
                    return;

                });
            }
        });

It works fine, but the compiler throws out:

auth-guard.service.ts(34,23): error TS2339: Property 'children' does not exist on type '{ name: string; url: string; icon: string; uviewable: string; badge: { variant: string; }; } | { ...'. Property 'children' does not exist on type '{ name: string; url: string; icon: string; uviewable: string; badge: { variant: string; }; }'.

Which is this line:

x.children.forEach(function(data, key){

Here is how the navigation looks like:

  export const navigation = [
  {
    name: 'Dashboard',
    url: '/dashboard',
    icon: 'icon-speedometer',
    uviewable: '*',
    badge: {
      variant: 'info'
      //text: 'NEW'
    }
  },
  {
      name: 'New Leads',
      url: '/sales',
      icon: 'icon-map',
      uviewable: '*',
      children: [
          {
              name: 'Lead Entry',
              url: '/sales/leadentry',
              icon: 'icon-layers',
              uviewable: '*'
          },
          {
              name: 'Upload Leads',
              url: '/sales/leadup',
              icon: 'icon-cloud-upload',
              uviewable: '*'
          }
      ]
  }, //etc..

Upvotes: 0

Views: 50

Answers (1)

Brendan Whiting
Brendan Whiting

Reputation: 504

You can also use bracket notation x['children'] instead of dot notation x.children, and then the compiler will stop complaining.

But yes, it would be good to make an interface, which would make the compiler happy and would help you out in the long run. You can have optional properties:

interface NavigationItem {
  name: string;
  url: string;
  icon: string;
  uviewable: string;
  badge?: any;
  children?: NavigationItem[]
}

Upvotes: 1

Related Questions