无法识别扩展快递请求对象

时间:2020-03-30 12:36:03

标签: typescript

我在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 }

我扩展了快递请求对象(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

1 个答案:

答案 0 :(得分:1)

您对Express的声明是错误的。

它看起来应该像这样:

declare global {
  namespace Express {
    interface Response {
      httpProblemJSON(problemDocument: ProblemDocument): void
    }
  }
}
相关问题