簡體   English   中英

擴展 Typescript 中的 Express 中間件

[英]Extend Express Middleware in Typescript

我目前正在使用 Express 和 Typescript 編寫 REST API 但我無法擴展 Express 的請求/響應。

我的 IDE 不再抱怨,但 Typescript 在編譯時拋出 TS2339 錯誤, error TS2339: Property 'jsonStatusError' does not exist on type 'Response<any, Record<string, any>>'.

我有一個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 中添加任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM