【发布时间】: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