TypeScript Express错误功能 [英] TypeScript Express Error Function

查看:53
本文介绍了TypeScript Express错误功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Typescript中进行编码时,错误处理函数的四个参数的类型是什么?

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

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

我正在使用VS Code,但未提供任何提示.在所有四个参数下都出现红色的摆动线.

I am using VS Code and no hints are offered. I get red wiggly lines under all four parameters.

错误显示参数隐式具有'any'类型".实际上,我对此消息感到困惑.如果将其视为 any 类型,那不是一个有效的选择吗?

The error says "Parameter implicitly has 'any' type". Actually I am confused with this message. If it treats it as an any type, then isn't that a valid choice?

推荐答案

该函数本身具有以下签名(取自

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

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

因此,您可以将函数声明为 ErrorRequestHandler 类型的变量,或者根据该定义键入参数.

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

注意:"express-serve-static-core"的类型是由"express"的类型导入的,这正是我在上面寻找的定义的地方.

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

关于与隐式 any 有关的第二个问题,是导致问题的隐式"部分,如果您明确键入 any ,则不会会出现任何错误(但也不会有任何输入).

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).

您还可以在编译器配置中禁用 noImplicitAny ,但我个人不建议这样做,因为它可以保护您免受几类错误的侵害.

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.

这篇关于TypeScript Express错误功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆