How to add Typescript definitions to Express req & res

后端 未结 4 1898
梦毁少年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:17

    The best way to do this is like so.

    // create some shared types in your project

    import { Request, Response, NextFunction } from 'express';
    export type MiddlewareFn = (req: Request, res: Response, next: NextFunction) => void;
    

    // then use the above types:

    import {MiddlewareFn} from './my-types.d.ts'
    
    router.get('/foo', <MiddlewareFn>function (req, res, next) {
    
       // ....
    });
    
    0 讨论(0)
  • 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) => {
      ...
    };
    
    0 讨论(0)
  • 2021-02-07 05:21

    Rather than installing types(@types/express) you should also define request parameters. Since every parameter is string, interface should base on dictionary.

    Here is an inline route handler:

    interface GetParams {
      [key: string]: string
      paramName: string
    }
    
    router.get<GetParams>('/:paramName', (req, res) => {
      res.send('Parameter is ' + req.params.paramName)
    })
    
    
    0 讨论(0)
  • 2021-02-07 05:22

    You can use ES6 style named imports to import only the interfaces you need, rather than import * as express from 'express' which would include express itself.

    First, make sure you have installed the type definitions for express (npm install -D @types/express).

    Example:

    // middleware/authCheck.ts
    import { Request, Response, NextFunction } from 'express';
    
    export const authCheckMiddleware = (req: Request, res: Response, next: NextFunction) => {
      ...
    };
    
    // server.ts
    import { authCheckMiddleware } from './middleware/authCheck';
    app.use('/api', authCheckMiddleware);
    

    Currently using TypeScript 2.3.4 and @types/express 4.0.36.

    0 讨论(0)
提交回复
热议问题