【问题标题】:Extend Express Middleware in Typescript在 Typescript 中扩展 Express 中间件
【发布时间】:2021-06-09 11:31:56
【问题描述】:

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

我的 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"]
}

我错过了什么?

【问题讨论】:

    标签: node.js typescript express middleware


    【解决方案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 添加任何内容。

    【讨论】:

    • 是的,很抱歉我花了这么长时间才接受它作为答案。
    猜你喜欢
    • 2019-05-30
    • 2021-01-12
    • 2021-05-30
    • 1970-01-01
    • 2020-08-12
    • 2016-04-07
    • 2015-11-05
    • 2016-09-19
    • 2021-01-07
    相关资源
    最近更新 更多