无法识别扩展的快速请求对象



我在TypeScript(3.8.3(中创建了一个全局快递请求错误处理程序

import express from 'express'
import { ProblemDocument } from 'http-problem-details'
const registerExpressProblemJsonResponse = (): void => {
express.response.httpProblemJSON = function(problemDocument): void { // line 5
this.set('Content-Type', 'application/problem+json')
this.status(problemDocument.status)
this.send(problemDocument)
}
}
export { registerExpressProblemJsonResponse }
import { NextFunction, Request, Response } from 'express'
const GlobalRequestErrorHandler = (logger: any) => {
return (
err: Error,
req: Request,
res: Response,
next: NextFunction
): void => {
logger.error(`${req.method} ${req.url} Error: ${err}`, { error: err })
if (!res.headersSent) {
return res.httpProblemJSON( // line 25
new ProblemDocument({ status: 500, type: 'https://tempuri.org/error' })
)
} else {
logger.warn(
`[global-request-error-handler] ${req.method} ${req.url} has an error path returning a response already`
)
}
}
}
export { GlobalRequestErrorHandler }

我已经扩展了express请求对象(src/types/types.d.ts(:

import { ProblemDocument } from 'http-problem-details'
declare namespace Express {
export interface Response {
httpProblemJSON(problemDocument: ProblemDocument): void
}
}

这是我的tsconfig.json:

{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"declaration": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": ["node_modules/*", "src/types/*"]
}
},
"include": ["src/**/*"]
}

我已经安装了"@types/express": "^4.17.3""express": "^4.17.1"

当运行tsc时,我会得到以下错误:

src/index.ts:5:20 - error TS2339: Property 'httpProblemJSON' does not exist on type 'Response<any>'.
5   express.response.httpProblemJSON = function(
~~~~~~~~~~~~~~~
src/index.ts:25:18 - error TS2339: Property 'httpProblemJSON' does not exist on type 'Response<any>'.
25       return res.httpProblemJSON(
~~~~~~~~~~~~~~~

Found 2 errors.

我在这里做错了什么?

GitHub Repo

您对Express的声明是错误的。

它假设看起来像这样:

declare global {
namespace Express {
interface Response {
httpProblemJSON(problemDocument: ProblemDocument): void
}
}
}

最新更新