【问题标题】:Type 'Actionmodel' is not assignable to type 'boolean'类型“Actionmodel”不可分配给类型“布尔”
【发布时间】:2019-10-25 03:45:39
【问题描述】:

我需要在列表中找到对象。

这是我的清单:

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”不可分配给类型“布尔”。

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

【问题讨论】:

  • 哪一行报错
  • @Sajeetharan 在这一行:const find = this.dynamic.dynamicModel.find(x =&gt; x.actionsVM.find(z =&gt; z.actionEnglishName === this.AccessName));
  • @kianoushdortaj this.AccessName 的类型是什么,你在哪里声明的?
  • @MaihanNijat 我更新了问题
  • 能否请您在问题中也添加 DynamicPermissionService 代码

标签: javascript angular typescript


【解决方案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 对@987654341 的定义相匹配@方法。

【讨论】:

    猜你喜欢
    • 2019-06-07
    • 2023-01-18
    • 2019-11-04
    • 2017-12-28
    • 2016-11-12
    • 1970-01-01
    • 2021-04-17
    • 2020-02-07
    • 1970-01-01
    相关资源
    最近更新 更多