检查对象的属性是否存在会引发编译错误

时间:2017-12-11 22:50:47

标签: angular typescript object

当对象的属性存在时,如何只在Angular 4(TypeScript)中运行某些代码?我试过这段代码:

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;

                });
            }
        });

它工作正常,但编译器抛出:

  

auth-guard.service.ts(34,23):错误TS2339:财产'儿童'类型' {name:string; url:string; icon:string; uviewable:string;徽章:{variant:string; }; } | {...'。     物业'儿童'类型' {name:string; url:string; icon:string; uviewable:string;徽章:{variant:string; }; }'

这一行:

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

以下是导航的样子:

  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..

1 个答案:

答案 0 :(得分:0)

您也可以使用括号表示法x['children']代替点符号x.children,然后编译器将停止抱怨。

但是,是的,制作一个接口会很好,这会让编译器感到高兴并且从长远来看会帮助你。您可以拥有可选属性:

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