0

My question is similar with TypeScript Express Error Function.

BUT the point of question is different. Why does the TypeScript cannot recognize the type of Express's error handler format?

I've also installed @type/express module. When I change

// doesn't work showing type checking error
app.use((err, req, res, next) => {
    // SOMETHING
});

into

// works.
app.use((err: any, req:express.Request, res: express.Response, next: express.NextFunction) => {
    // SOMETHING
});

, it works.

6991httam
  • 305
  • 4
  • 14

1 Answers1

1

Hit ctrl, cmd + click and you can see the documentation

export interface IRouterHandler<T> {
    (...handlers: RequestHandler[]): T;
    (...handlers: RequestHandlerParams[]): T;
    // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.)
    <P = ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = ParsedQs>(...handlers: Array<RequestHandler<P, ResBody, ReqBody, ReqQuery>>): T;
    // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.)
    <P = ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = ParsedQs>(...handlers: Array<RequestHandlerParams<P, ResBody, ReqBody, ReqQuery>>): T;
}

Clearly says It's a Generic Type and needs to be passed explicitly.

So would recommend passing types explicitly, another reason might be the function might be overloaded too much to infer any type.

Because in some cases infers types for other methods such as get, post.

sameer kashyap
  • 1,121
  • 1
  • 9
  • 14
  • I had a look at the doc you told me. I'm not 100% get what it does mean, but my question is solved. Thank you for letting me know :) – 6991httam Jan 10 '21 at 08:37