ウェブサイト検索

node.js - TypescriptでExpressミドルウェアを拡張する


私は現在、ExpressとTypeScriptでREST APIを書いていますが、ExpressのRequest/Responseを拡張するのに問題があります。

私のIDEはもう警告を出さなくなりましたが、Typescriptはコンパイル時に TS2339 エラーを投げます:error TS2339: 型 'Response<any, Record<string, any>>' にプロパティ 'jsonStatusError' は存在しません。

私は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"]
}

何が足りないのですか?

回答 #1

この試みは私にとってうまくいきます。

ソースフォルダに 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 に何も追加しません。