重复项: Extend Express Request object using Typescript
import { Router } from 'express';
import * as uuid from 'uuid';
我正在使用打字稿3.6.4。我要扩展express.Request类型,因为我想添加id字段:
interface request extends Express.Request {
id: string
}
如果我使用设置ID的中间件创建post方法:
router.post('/orders', (req: request, _res: express.Response, next) => {req.id = uuid.v1(); next();}, async function (req: request, res: express.Response) {
...
});
但是我在要求:请求中遇到错误
tscongif.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": [
"es5",
"es6",
"dom",
"es2017",
"esnext.asynciterable"
],
"strict": true,
"alwaysStrict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": false,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"baseUrl": "./src",
"esModuleInterop": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"forceConsistentCasingInFileNames": true,
"sourceMap": true,
"outDir": "./dist",
"removeComments": true
},
"exclude": ["node_modules"],
"include": [
"./src/**/*", "./src/**/*.tsx", "./src/**/*.ts"
]
}
答案 0 :(得分:1)
我认为您正在寻找declaration merging
您可以合并接口。 在global.d.ts中声明您的接口,ts会合并它。
declare global {
declare module 'express' {
export interface Request {
id: string;
}
}
}
然后您就可以在应用程序中的任何地方使用它
const id = Express.request.id;
const anythingElseFromRequestInterface = Express.request.baseUrl;
答案 1 :(得分:0)
这个对我有用!
declare module "express" {
interface Request {
id: string
}
}