How to add Typescript definitions to Express req & res

后端 未结 4 1892
梦毁少年i
梦毁少年i 2021-02-07 04:57

I have a set of controller functions for my REST API and I\'m getting lots of the following

error TS7006: Parameter \'req\' implicitly has an \'any\' type.
         


        
4条回答
  •  [愿得一人]
    2021-02-07 05:20

    It can be daunting to type the arguments every time you need to write middleware functions so you can just type the whole function directly too.

    npm i @types/express --save-dev ("@types/express": "^4.17.0")
    

    After installing typings..

    // This can be shortened..
    import { Request, Response, NextFunction } from 'express';
    export const myMiddleware = (req: Request, res: Response, next: NextFunction) => {
      ...
    };
    
    // to this..
    import { RequestHandler } from 'express';
    export const myMiddleware: RequestHandler = (req, res, next) => {
      ...
    };
    
    // or in case it handles the error object
    import { ErrorRequestHandler } from 'express';
    export const myMiddleware: ErrorRequestHandler = (err, req, res, next) => {
      ...
    };
    

提交回复
热议问题