简体   繁体   中英

How do I fix the error? Typescript: Type 'ErrorRequestHandler' is not assignable to type 'IMiddleware'

In the following code, I got an error with type reassignment:

export default class AbstractController extends Middleware {

    get middleware(): Express.RequestHandler | Express.ErrorRequestHandler { // (6,22)
        //...
    }

}

Error text:

src/controller/AbstractController.ts(6,22): error TS2415: Class 'AbstractController' incorrectly extends base class 'Middleware'.
  Types of property 'middleware' are incompatible.
    Type 'ErrorRequestHandler | RequestHandler' is not assignable to type 'IMiddleware'.
      Type 'ErrorRequestHandler' is not assignable to type 'IMiddleware'.

Declare RequestHandler and ErrorRequestHandler interfaces:

interface RequestHandler {
    (req: Request, res: Response, next: NextFunction): any;
}

interface ErrorRequestHandler {
    (err: any, req: Request, res: Response, next: NextFunction): any;
}

Declare Middleware class:

export interface IMiddleware {
    (req: http.IncomingMessage, res: http.ServerResponse): void;
}

export default class Middleware {

    get middleware(): IMiddleware {
        throw new Error('Не определен middleware.');
    }

}

I need to understand not how to fix it, but what is the cause of the error.

The Middleware class expects a IMiddleware as return type of middleware() .

Your interfaces should extend IMiddleware !

interface RequestHandler extends IMiddleware {
    (req: Request, res: Response, next: NextFunction): any;
}

interface ErrorRequestHandler extends IMiddleware {
    (err: any, req: Request, res: Response, next: NextFunction): any;
}

However, ErrorRequestHandler 's signature does not match IMiddleware

Maybe you should create a second interface to represent it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM