TS2345:类型'Role []'的参数不能分配给类型'object []'的参数

时间:2020-10-27 07:52:20

标签: arrays angular object

我正在使用Angular 8。

我正面临着这个'Role[]' is not assignable to parameter of type 'object[]'

我错误地实施了checkRoleExistallowedToAccess吗?

角色枚举类:

export enum Role {
  A = 'role-a',
  B = 'role-b',
  C = 'role-c',
  D = 'role-d',
  E = 'role-e',
}

我有一个util类:

export function allowedToAccess(allowedRoles: object[], currentRoles: object[]) {
  let i: number;

  if (currentRoles === undefined || currentRoles === null || allowedRoles === undefined || allowedRoles === null) {
    return false;
  }
  console.log('allowedRoles:' + allowedRoles);
  console.log('currentRoles:' + currentRoles);

  allowedRoles.forEach(givenAllowedRoles => checkRoleExist(givenAllowedRoles, currentRoles))

  for(i = 0; i < allowedRoles.length; i++) {
    if (checkRoleExist(allowedRoles[i], currentRoles)) {
      return true;
    }
  }

  return false;
}

function checkRoleExist(allowedRoles: object, currentRoles: object[]) : boolean {

  /**
   * allowedRoles : [[Role.A, Role.B], Role.C, [Role.D], Role.E]
   * currentRoles : [Role.A, Role.B]
   */

  /**
   * allowedRoles : [[Role.A, Role.B], Role.C, [Role.D], Role.E]
   * currentRoles : [Role.A]
   */

  /**
   * allowedRoles : [[Role.A, Role.B], Role.C, [Role.D], Role.E]
   * currentRoles : [Role.E]
   */

  /**
   * allowedRoles : [[Role.A, Role.B], Role.C, [Role.D], Role.E]
   * currentRoles : [Role.A, Role.B, Role.F]
   */

  // check if allowedRoles is an array
  if (Array.isArray(allowedRoles)) {
    allowedRoles.forEach(allowedRole => {
      if (!currentRoles.includes(allowedRole)) {
        return false;
      }
    })

    return true;
  }

  // allowedRoles is an object
  return currentRoles.includes(allowedRoles);
} 

在我的标头类中:

export class HeaderComponent implements OnInit {
  ...

  constructor(
    ...
  ) {}

  ngOnInit() {
this.credentialsService.currentUserSubject.subscribe((u: User) => {
      const currentUserRoles: Role[] = u.role.slice();

      this.navigationlinks = [
        {
          id: 'library',
          label: 'library',
          index: 0,
          icon: '../assets/header/library.svg',
          disabledIcon: '../assets/header/library_disabled.svg',
          render: allowedToAccess([Role.A, Role.B], currentUserRoles),
          isActive: false,
          subLinks: [
...

错误日志:

src/app/shell/header/header.component.ts:43:59 - error TS2322: Type 'Role.A' is not assignable to type 'object'.

43           render: allowedToAccess([Role.A, Role.B], currentUserRoles),

0 个答案:

没有答案