node.js - 在 Typescript 中擴展 Express 中介軟體
我目前正在使用 Express 和 TypeScript 撰寫 REST API,但我在擴展 Express 的 Request/Response 時遇到了困難。
我的 IDE 不再報錯,但在使用 編譯時,Typescript 會拋出 TS2339 錯誤:error TS2339: 屬性 'jsonStatusError' 不存在於類型 'Response
我有一個 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 中添加任何內容。
