在 Typescript 中扩展 Express 中间件

Extend Express Middleware in Typescript

我目前正在使用 Express 和 Typescript 编写 REST API,但我在扩展 Express 的 Request/Response 时遇到问题。

我的 IDE 不再抱怨了,但是 Typescript 在使用 error TS2339: Property 'jsonStatusError' does not exist on type 'Response<any, Record<string, any>>'.

编译时抛出 TS2339 错误

我有一个jsonResponseMiddleware

import { NextFunction, Request, Response } from 'express';

export default (req: Request, res: Response, next: NextFunction) => {
  res.jsonStatusOk = (obj = {}) => res.json({ status: 'ok', data: obj });
  res.jsonStatusError = (obj = {}) => res.json({ status: 'error', data: obj });
  next();
};

和一个main.d.ts

declare namespace Express {
  export interface Request {}
  export interface Response {
    // type definition for jsonResponseMiddleware
    jsonStatusOk: (obj: any) => void;
    jsonStatusError: (obj: any) => void;
  }
}

我的tsconfig.json

{
  "compilerOptions": {
      "lib": ["es6"],
      "target": "es6",
      "module": "commonjs",
      "moduleResolution": "node",
      "outDir": "./build",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "sourceMap": true,
      "paths": {},
      "allowJs": true,
      "baseUrl": ".",
      "strict": false,
      "noEmitOnError": true,
  },
  "include": ["src/**/*"],
  "files": ["./src/types/main.d.ts"]
}

我错过了什么?

这个尝试对我有用。

在您的源文件夹中添加名为 global.ts 的文件:

declare global {
  namespace Express {
    export interface Response {
      jsonStatusOk: (obj: any) => void;
      jsonStatusError: (obj: any) => void;
    }
  }
}

然后在 index.ts:

import './global';

[...]

最后这应该起作用了:

import { Request, Response, NextFunction } from 'express';

export default (req: Request, res: Response, next: NextFunction) => {
  res.jsonStatusOk = (obj = {}) => res.json({ status: 'ok', data: obj });
  res.jsonStatusError = (obj = {}) => res.json({ status: 'error', data: obj });
  next();
};

我没有向我的 tsconfig.json 添加任何内容。