Search code examples
node.jstypescriptexpresspassport.js

Typescript no overload matches this call


I'm new to TypeScript and I'm currently stuck. I have a nodejs and express app.

I'm getting the following error: No overload matches this call.

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,

This is my route file

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)

This is my middleware file

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
}

    

Solution

  • Your exports from the middleware file have been set up incorrectly.

    You are constructing an object with one property, isLoggedIn, which is the handler function, and then exporting that object as the default export.

    So, when you import the default export from this file in the line:

    import isLoggedIn from '@middleware/user';
    

    Now isLoggedIn is equal to the value of the default export. i.e. isLoggedIn is an object with one property isLoggedIn that is equal to the handler function. So, instead of passing a function to route('/').get(...) like it expects, you are passing it an object.

    You can use a named export from your middleware file instead:

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

    Then import it by name:

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