Node + Express router + Type Script : string arg is not assignable to requesthandlerparams type

Viewed 2552

I'm following a tuto to create a full rest api, then, i create a TS class that export a new express router :

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


export class TourRouter {
public router: Router;

constructor() {
    this.router = Router();

    this.init();
}

public init(): void {
    this.router.get(
        '/',
        this.getTours
    );
}

private getTours(request: Request, response: Response, next: NextFunction) {
    // Some JSON
    const tours = {
        "now": "2018-09-09 18:40:00",
        "date": "2018-09-09",
        "tours": [
            {
                "time": "8",
                "places": 8,
                "isPast": false
            },
            {
                "time": "11",
                "places": 8,
                "isPast": false
            },
            {
                "time": "14",
                "places": 8,
                "isPast": false
            },
            {
                "time": "17",
                "places": 8,
                "isPast": false
            }             
        ]
    };

    response.send(tours);
}
}

const tourRoutes = new TourRouter();
tourRoutes.init();

export default tourRoutes.router;

When i want to use this new Router in my App.ts as follow, i'm getting a TS error and the build failed with the message :

Argument of type 'string' is not assignable to parameter of type 'RequestHandlerParams'

The use statement is :

    private _routes(): void {
    let router = express.Router();

    router.get('/', (request, response, next) => {
        response.json({
            message: 'Hello World'
        });
    });

    this.express.use('/', router);
    this.express.use('/api/v1/tours', TourRouter);
}

As if TourRouter, in my case was not a Router as i expect but something else, but don't know why. What i'm missing ?

Regards

2 Answers

It sounds like you are importing the TourRouter class instead of the actual router, which is the default export. Replace import { TourRouter } from './routes/TourRouter'; with import TourRouter from './routes/TourRouter';. You might want to import the router using a name other than TourRouter to avoid confusion.

TypeScript knows that the arguments you are passing to this.express.use do not match any of the valid overload signatures, but it doesn't know which overload signature you intended to use. It (incorrectly) guesses the (...handlers: RequestHandlerParams[]) => T signature, which explains the strange error that the string path is not assignable to RequestHandlerParams.

Related