TypeScript中使用Express的app.response.sendWrapped报属性不存在错误求解决
解决Express Response扩展sendWrapped时的TypeScript类型错误
TypeScript报错是因为默认的Express Response类型里没有sendWrapped方法,你需要扩展Express的类型定义,让TypeScript识别这个新增方法。
解决步骤:
创建类型声明文件
在项目中新建一个类型声明文件,比如src/types/express.d.ts(路径可根据项目结构调整,只要能被TypeScript扫描到即可)。扩展Response接口
在声明文件中添加以下代码,扩展Express的Response接口:
import { Response } from 'express'; declare module 'express' { interface Response { sendWrapped: (statusCode: number, message: string, data?: any) => this; } }
- 确保TypeScript识别声明文件
检查tsconfig.json,确保include数组包含声明文件所在路径,示例配置:
{ "compilerOptions": { // 其他配置项 }, "include": ["src/**/*", "src/types/**/*"] }
- 重新实现扩展方法
此时回到你的代码,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
相关产品推荐
相关产品推荐

