我正在将 TypeScript 用于具有目录结构的面向微服务的 monorepo 项目:
- root
- backend
- shared-files
-src...
- tsconfig.json
- microservice1
-src...
- tsconfig.json
- microservice2
-src...
- tsconfig.json
...
为了丰富请求界面,我使用了 Extend Express Request object using Typescript 中接受的答案,即我创建了一个文件 @types/express/index.d.ts
:
declare namespace Express {
export interface Request {
extraAttribute: string;
}
}
这个解决方案对我来说效果很好,但是我希望这个界面(以及其他功能)在不同的微服务中可用。
我使用 shared-files
作为引用设置了项目引用。我可以毫无问题地使用 shared-files
中的类型,但是 declare namespace
/export interface
似乎没有生效,并且我在构建时得到 Property 'extraAttribute' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'
。
tsconfig 文件供参考:
microservice1/tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"target": "es5",
"module": "commonjs",
"outDir": "./build",
"rootDir": "./src",
"strict": true,
"baseUrl": "./src",
"paths": {"@shared-files/*": ["../../shared-files/src/*"]},
"typeRoots": ["./node_modules/@types", "../shared-files/src/@types", "./src/@types"],
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"references": [
{ "path": "../shared-files"}
]
}
shared-files/tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"declarationMap": true,
"outDir": "./build",
"composite": true,
"strict": true,
"baseUrl": "./",
"typeRoots": ["./node_modules/@types", "./src/@types"],
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"references": []
}