[英]Property does not exist on type when using custom type definition
我試圖在 expressJS 響應中擁有自定義屬性(函數),但我真的無法理解為什么我不斷得到該property does not exist on type
。
我已經定義了一個自定義定義文件:
索引.d.ts
/* eslint-disable no-unused-vars */
interface APIResponse {
status?: number,
message?: string | null,
data?: any
}
declare global {
namespace Express {
interface Response {
showDefaultErrorPage: (status: number) => Response<any, Record<string, any>, number>
showErrorPage: (status: number) => Response<any, Record<string, any>, number>
success: (options: APIResponse) => Response<any, Record<string, any>, number>
error: (options: APIResponse) => Response<any, Record<string, any>, number>
}
}
}
快遞中間件
const responseHelper = (req: Request, res: Response, next: NextFunction) => {
res.showDefaultErrorPage = (status: number = 500) => { // Error here
// ...
}
res.showErrorPage = (status: number) => { // Error here
// ...
}
res.success = (options = {}) => { // Error here
const {
status = 200,
message = null,
data
} = options
return res.status(status).json({
status,
message: message || getStatusMessage(status) || 'Success',
data
})
}
res.error = (options = {}) => { // Error here
const {
status = 500,
message = null
} = options
return res.status(status).json({
status,
message: message || getStatusMessage(status) || 'Server error'
})
}
next()
}
export default responseHelper
tsconfig.json
"target": "es2016",
"module": "commonjs",
"rootDir": "./src",
"moduleResolution": "node",
"typeRoots": [
"./src/@types/express"
],
"outDir": "./build",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
您可以嘗試將index.d.ts
添加到 `tsconfig.json' 中的files
條目中:
"files": [
"index.d.ts"
]
您也可以嘗試exporting
Response
接口。 像這樣的東西:
declare module 'express' {
export interface Response {
showDefaultErrorPage: (status: number) => Response<any, Record<string, any>, number>
showErrorPage: (status: number) => Response<any, Record<string, any>, number>
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.