【问题标题】:Typescript no overload matches this call打字稿没有重载匹配这个调用
【发布时间】:2022-02-03 09:03:20
【问题描述】:

我是 TypeScript 的新手,目前陷入困境。我有一个 nodejs 和 express 应用程序。

我收到以下错误:没有重载匹配此调用。

The last overload gave the following error.
    Argument of type '{ isLoggedIn: (req: Request<ParamsDictionary, any, any, QueryString.ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction) => Response<...> | undefined; }' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
      Type '{ isLoggedIn: (req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction) => Response<...> | undefined; }' is missing the following properties from type '(ErrorRequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>> | RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<...>>)[]': length, pop,

这是我的路线文件

export {}

import express, { Router } from 'express';

import lessons from '@controllers/lessons';
import isLoggedIn from '@middleware/user';

const lessonRoutes: Router = express.Router();


lessonRoutes.route('/')
        .get(isLoggedIn, lessons.lessonForm)

这是我的中间件文件

import { Request, Response, NextFunction } from 'express';

const isLoggedIn = (req: Request, res: Response, next: NextFunction) => {
    if (!req.isAuthenticated()) {
        return res.status(401).json({
            error: "User must sign in"
          })
    }
    next();
}

export default {
    isLoggedIn
}

    

【问题讨论】:

    标签: node.js typescript express passport.js


    【解决方案1】:

    您从中间件文件导出的设置不正确。

    您正在构造一个具有一个属性 isLoggedIn 的对象,该属性是处理函数,然后将该对象导出为默认导出。

    因此,当您从该文件中导入默认导出时:

    import isLoggedIn from '@middleware/user';
    

    现在isLoggedIn 等于默认导出的值。即isLoggedIn 是一个具有一个属性isLoggedIn 的对象,该属性等于处理函数。因此,不是像预期的那样将函数传递给route('/').get(...),而是传递给它一个对象。

    您可以改用中间件文件中的命名导出:

    export const isLoggedIn = (...) => ...;
    

    然后按名称导入:

    import {isLoggedIn} from '@middleware/user';
    

    【讨论】:

      猜你喜欢
      • 2020-06-14
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 2020-07-11
      • 1970-01-01
      相关资源
      最近更新 更多