【发布时间】:2021-07-29 20:11:22
【问题描述】:
对于使用express-session 包的项目,我试图通过简单地添加用户密钥来改变session 对象。
req.session.user = 123;
来自this question's 接受的答案,我知道我可以使用声明合并来扩展SessionData 接口,使用我自己的接口。
查看各种开源项目,例如HospitalRun components repository,我注意到他们在tsconfig.json 文件中的tsconfig.json 文件中有types 目录,就像这样。
"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,
},
}
我尝试做同样的事情,在此文件夹 (~/types/) 的根目录中创建了一个名为 express-session.d.ts 的文件,其内容如下:
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,使用相同的文件夹。
【问题讨论】:
-
您是否有指向演示此问题的 Web IDE 的链接,或您的问题的其他 minimal reproducible example?我怀疑问题是由于您的配置造成的,很难调试看不见的视线。
-
@jcalz 添加了我的示例!
标签: javascript node.js typescript express session