对于使用的项目express-session
包,我正在尝试改变session
只需添加用户密钥即可实现对象。
req.session.user = 123;
来自(哪里这个问题的 https://stackoverflow.com/q/65108033/2989034接受的答案,我知道我可以使用声明合并来扩展SessionData
界面,使用我自己的界面。
查看各种开源项目,例如HospitalRun 组件存储库 https://github.com/HospitalRun/components/tree/master我注意到他们有types
他们的目录中tsconfig.json
文件下的include
像这样的部分。
"include": [
"src",
"types"
]
我的整个tsconfig.json
看起来像这样,它位于项目的根目录中。
{
"include": [
"types",
"src",
],
"exclude": [
"node_modules"
],
"compilerOptions": {
"lib": [
"esnext",
"esnext.asynciterable"
],
"baseUrl": ".",
"skipLibCheck": true,
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"outDir": "build",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"strictPropertyInitialization": false,
},
}
我尝试做同样的事情,一起创建一个名为express-session.d.ts
在此文件夹的根目录中(~/types/
),具有以下内容:
import session from 'express-session';
declare module 'express-session' {
interface SessionData {
user: any;
}
}
但是,我不断收到的错误是这样的。
Property 'user' does not exist on type 'Session & Partial<SessionData>'
然而,当我将这段代码添加到用于改变会话对象的代码上方时,我不再遇到问题。但这似乎不是正确的方法。
另外,当我使用tsc src/index.ts --build
代替ts-node src/index.ts
它也有效。
我在这里做错了什么?如何解决这个问题?我也尝试使用typeRoots
,使用同一文件夹。