egg icon indicating copy to clipboard operation
egg copied to clipboard

在使用egg.js + egg-passport + passport-local 的时候,遇到了函数参数类型不匹配的问题

Open hythl0day opened this issue 4 years ago • 1 comments

最小可复现仓库

https://github.com/hythl0day/eggjs_passport_test

复现步骤,错误日志以及相关配置

(类型文件安装自:@types/passport-local)

打开app.js文件

内容完全复制自官方示例代码但改写为typescript的方式。

然后在下面这个函数中遇到了类型错误的提示

  app.passport.use(new LocalStrategy({
    passReqToCallback: true,
  }, (req, username, password, done) => {
    // format user
    const user = {
      provider: 'local',
      username,
      password,
    };
    // debug('%s %s get user: %j', req.method, req.url, user);
    app.passport.doVerify(req, user, done);
  }));

在:doVerify(req, user, done),这一行中,req的参数不匹配。

编辑器提示:

Argument of type 'Request<ParamsDictionary, any, any, ParsedQs>' is not assignable to parameter of type 'Request'.
  Type 'Request<ParamsDictionary, any, any, ParsedQs>' is missing the following properties from type 'Request': files, acceptJSON, queries, req, and 14 more.ts(2345)

而且这个错误无法忽略,执行 npm run dev会被中断。

按照 @types/passport-local的定义,LocalStrategy的构造函数如下:

declare class Strategy extends PassportStrategy {
    constructor(
        options: IStrategyOptionsWithRequest,
        verify: VerifyFunctionWithRequest
    );
    // ...
    name: string;
}

其中VerifyFunctionWithRequest的定义如下:

interface VerifyFunctionWithRequest {
    (
        req: express.Request,
        username: string,
        password: string,
        done: (error: any, user?: any, options?: IVerifyOptions) => void
    ): void;
}

可以看到这里的req类型是 express.Request,在@types/express中的定义是:

    interface Request<P = core.ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = core.Query> extends core.Request<P, ResBody, ReqBody, ReqQuery> { }

而doVerify是来自 egg-passport的type定义:

  doVerify<TUserPayload = any, TUser = any>(req: Request, user: TUserPayload, done: (err: any, user?: TUser) => void): void;

这里的req的类型来自eggjs自己的egg-multipart文件

  interface Request {
    /**
     * Files Object Array
     */
    files: EggFile[];
  }

要怎么解决这两个req类型不同导致无法在typescript中使用的问题?

相关环境信息

  • Node 版本:v14.15.0
  • Egg 版本:2.6.1

hythl0day avatar Nov 05 '20 08:11 hythl0day

只能用 as 大法了

whxaxes avatar Nov 12 '20 03:11 whxaxes