[英]Type not being checked in custom response structure in Express
我从 typescript 开始,遇到了一个障碍,我无法弄清楚为什么没有验证类型。
路线
app.use((req: Request, res: Response) => {
// here 404 is a string but should be a number according to type defined but no error is shown
return res.error({ status: '404', message: 'The API route does not exist' })
})
中间件
interface APIResponse {
status: number,
message?: string | null,
data?: any
}
const responseHelper = (req: Request, res: Response, next: NextFunction) => {
res.showDefaultErrorPage = (status: number = 500) => {
//...
}
res.success = (options: APIResponse) => {
const {
status = 200,
message = null,
data
} = options
//...
}
res.error = (options: APIResponse) => {
const {
status = 500,
message = null
} = options
//...
}
next()
}
export default responseHelper
快速响应的自定义类型定义
/* eslint-disable no-unused-vars */
declare namespace Express {
interface Response {
showDefaultErrorPage?: any
showErrorPage?: any
success?: any
error?: any
}
}
您可以将您的类型定义更改为:
declare namespace Express {
interface Response {
showDefaultErrorPage?: any
showErrorPage?: any
success?: (options: ApiResponse) => Response<any, Record<string, any>, number>
error?: (options: ApiResponse) => Response<any, Record<string, any>, number>
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.