类型“ Actionmodel”不可分配给类型“布尔”

时间:2019-06-10 18:14:47

标签: javascript angular typescript

我需要在list中找到对象。

这是我的列表:

export interface Controllermodel {
  controllerDisplayName: string;
  controllerFarsiName: string;
  roleId: number;
  controllerId: string;
  actionsVM: Actionmodel[];
}

export interface Actionmodel {
  displayName: string;
  actionEnglishName: string;
  actionId: number;
}

现在我需要在列表中查找对象,但是当我使用此代码时:

export class ValidatePermissionDirective implements OnInit {

  show: boolean;
  constructor(private templateRef: TemplateRef<any>,
              private viewContainerRef: ViewContainerRef
    ,         private dynamic: DynamicPermissionService) { }

  // tslint:disable-next-line:no-input-rename
  @Input('appValidatePermission') AccessName:string;

  ngOnInit() {
    this.ValidatePemission();
    if (this.show) {
      this.viewContainerRef.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainerRef.clear();
    }
  }
  ValidatePemission()
  {
    console.log(this.AccessName)
    const find = this.dynamic.dynamicModel.find(x =>
      x.actionsVM.find(z => z.actionEnglishName === this.AccessName));
      console.log(find)
      if (find) {
        console.log(false);
        this.show = false;
      } else {
        console.log(true);
        this.show = true;
      }
  }
}

但是当我使用此代码时,它向我显示此错误:

  

类型'Actionmodel'不能分配给类型'布尔'。

出什么问题了?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

添加!!以确保您的find结果为布尔值:

const find = this.dynamic.dynamicModel.find(x =>
  !!x.actionsVM.find(z => z.actionEnglishName === this.AccessName));

find使用一个参数:一个接受数组元素并返回boolean的函数。返回的对象将是找到的实例或undefined

const find = this.dynamic.dynamicModel.find(
    x => x.actionsVM.find(
        z => z.actionEnglishName === this.AccessName));

在内部find调用中,您有正确的答案:z.actionEnglishName === this.AccessName返回一个boolean

在外部find调用中,您将返回内部find的结果,该结果将是Actionmodel实例或值undefined。这些值可以强制为truefalse,但是Typescript希望将其明确。通过以!!开头,您可以确保“真实”值(如实例)将返回值true,而“虚假”值(如undefined)将返回值false,符合Typescript对find方法的定义。

相关问题