Search code examples
node.jstypescriptexpressmiddleware

Typing params with several middlewares | Typescript


I'm using Typescript, and while I'm trying to type parameters in Request, I get an error:

TS2769: No overload matches this call.   The last overload gave the following error.     Argument of type '(req: Request<IUpdateQA, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction) => Promise<...>' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.       Type '(req: Request<IUpdateQA, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction) => Promise<...>' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.         Types of parameters 'req' and 'req' are incompatible.           Type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' is not assignable to type 'Request<IUpdateQA, any, any, ParsedQs, Record<string, any>>'.             Types of property 'params' are incompatible.               Property 'id' is missing in type 'ParamsDictionary' but required in type 'IUpdateQA'.

My route:

QuestionAnswerRouter.delete('/:id', shopAuthMiddleware, QuestionAnswerController.delete );

My code (has error):

async delete(req: Request<{id: number}>, res: Response, next: NextFunction) {
   ...
}

And when I'm trying this, it works (Request has no generic):

async delete(req: Request, res: Response, next: NextFunction) {
   ...
}

Solution

  • Param type is always string.

    export interface ParamsDictionary {
        [key: string]: string;
    }
    

    Try to replace number by string and the error should not longer appear.

    async delete(req: Request<{id: string}>, res: Response, next: NextFunction) {
       ...
    }