You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中使用Express的app.response.sendWrapped报属性不存在错误求解决

解决Express Response扩展sendWrapped时的TypeScript类型错误

TypeScript报错是因为默认的Express Response类型里没有sendWrapped方法,你需要扩展Express的类型定义,让TypeScript识别这个新增方法。

解决步骤:

  1. 创建类型声明文件
    在项目中新建一个类型声明文件,比如src/types/express.d.ts(路径可根据项目结构调整,只要能被TypeScript扫描到即可)。

  2. 扩展Response接口
    在声明文件中添加以下代码,扩展Express的Response接口:

import { Response } from 'express';

declare module 'express' {
  interface Response {
    sendWrapped: (statusCode: number, message: string, data?: any) => this;
  }
}
  1. 确保TypeScript识别声明文件
    检查tsconfig.json,确保include数组包含声明文件所在路径,示例配置:
{
  "compilerOptions": {
    // 其他配置项
  },
  "include": ["src/**/*", "src/types/**/*"]
}
  1. 重新实现扩展方法
    此时回到你的代码,TypeScript不会再抛出类型错误:
app.response.sendWrapped = function (statusCode: number, message: string, data?: any) {
  return this.status(statusCode)
    .send({
      status: statusCode,
      message,
      data,
    });
};

可选:优化类型严谨性

如果不想使用any类型,可以改成泛型版本,让data的类型更明确:

类型声明:

import { Response } from 'express';

declare module 'express' {
  interface Response {
    sendWrapped: <T = unknown>(statusCode: number, message: string, data?: T) => this;
  }
}

实现代码:

app.response.sendWrapped = function <T = unknown>(statusCode: number, message: string, data?: T) {
  return this.status(statusCode)
    .send({
      status: statusCode,
      message,
      data,
    });
};

内容的提问来源于stack exchange,提问作者Wahyu Ramadan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 23:12:02