TypeScript Express Error Function

后端 未结 3 1431
星月不相逢
星月不相逢 2021-01-18 10:27

What are the types of the four parameters for the error handling function when coding in Typescript?

app.use((err: ??, req: ??, res: ??, next: ??) => { }         


        
3条回答
  •  梦谈多话
    2021-01-18 11:07

    The function itself has the following signature (taken from DefinitelyTyped):

    export type ErrorRequestHandler = (err: any, req: Request, res: Response, next: NextFunction) => any;
    

    So you can either declare the function as a variable of type ErrorRequestHandler or type the parameters according to that definition.

    Note: the typings for "express-serve-static-core" are imported by the typings for "express", which was where I looked for the above definition.

    Regarding your second question related to implicit any, it is the "implicit" part which is causing the problem, If you explicitly type as any then there won't be any error (but there won't be any typings either).

    You can also disable noImplicitAny in your compiler config but I wouldn't recommend it personally, as it protects you from several classes of bugs.

提交回复
热议问题