[英]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.