TS2345:'RolesGuard' 类型的参数不可分配给 'CanActivate' 类型的参数

TS2345: Argument of type 'RolesGuard' is not assignable to parameter of type 'CanActivate'

error TS2345: Argument of type 'RolesGuard' is not assignable to parameter of type 'CanActivate'. Types of property 'canActivate' are incompatible. Type '(req: any, context: ExecutionContext) => any' is not assignable to type '(context: ExecutionContext) => boolean | Promise | Observable'.

app.useGlobalGuards(new RolesGuard(new Reflector()));

这就是我的代码的样子。

app.useGlobalGuards(new RolesGuard(new Reflector()));
import { Guard, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs/Observable';
import { merge, reduce } from 'rxjs/operators';

import { from } from 'rxjs/observable/from'
import { Reflector } from '@nestjs/core';
import { getManager } from "typeorm";
import { MODULES, FEATURES } from '../constant';

@Guard()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) { }

  canActivate(req, context: ExecutionContext): Promise<boolean> {
    const { parent, handler } = context;
    const permissions = this.reflector.get<string[]>('Permission', handler);
    if (!permissions) {
      return new Promise((res, rej) => { res(false) });
    }
    .
    .
    .
    .
    //if there are more than two set of permissions
    if (permissions.length > 3) {
      let perms = Array.from(permissions);
      perms.splice(2, 1);
      let whereClause = perms.reduce((acc, val, index) => {
        let paramNo = index + 2;
        if (index % 2 === 0) {
          return `${acc}(module=$${paramNo}`;
        } else {
          return `${acc} AND feature=$${paramNo}) OR `
        }
      }, "");
      .
      .
      .
    }

    return entityManager.query(sql, params).then(res => {
      let perms = <Array<any>>res;
      let type = permissions[2].toLowerCase();
      if (type === 'view') {
        return perms.reduce((acc, val) => { return (val['canview'] || val['canedit']) || acc }, false);
      } else if (type === 'edit') {
        return perms.reduce((acc, val) => { return val['canedit'] || acc }, false);
      } else {
        return false;
      }
    });
  }
}

你的接口签名有误。出于某种原因,您添加了一个冗余 req 参数。

来自 NestJS 文档,这是守卫应该是什么样子的官方示例:


import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class RolesGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    return true;
  }
}

注意 canActivate 如何只有一个参数 - context: ExecutionContext。从错误消息中也可以看出这一点。

所以您应该可以通过删除 req.

来解决您的问题