对于使用 express-session
包的项目,我试图通过简单地添加用户 key 来改变 session
对象。
req.session.user = 123;
来自this question's 接受的答案,我知道我可以使用声明合并来扩展 SessionData
接口(interface),使用我自己的接口(interface)。
查看各种开源项目,例如 HospitalRun components repository我注意到他们在 include
部分下的 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>'
然而,当我将这段代码添加到我用于改变我的 session 对象的代码之上时,我就不再有问题了。不过,这似乎不是正确的方法。
此外,当我使用 tsc src/index.ts --build
而不是 ts-node src/index.ts
时,它也有效。
我在这里做错了什么?这怎么能解决?我还尝试使用 typeRoots
,使用相同的文件夹。
最佳答案
最新更新(2021 年 5 月 8 日)
使用ts-node
运行typescript程序时,即使在tsconfig.json中指定了typeRoots
,也无法识别自定义的.d.ts和提示符Property 'x
does not exist on type y` 错误。
根据 https://github.com/TypeStrong/ts-node/issues/1132#issuecomment-716642560
ts-node
的贡献者之一提出了多种解决方法。
这是其中之一:
在tsconfig.json
中指定file: true
标志通知ts-node
加载files
,include
和 exclude
启动时 tsconfig.json
中的选项
{
"ts-node": {
"files": true
},
"exclude": [...],
"compilerOptions": {
...
}
旧:(2021 年 5 月 7 日)
tsconfig.json
中不需要使用include
,路径不正确。编译器可以在目录和子目录下搜索ts文件
尝试删除它。并重启TS服务器。
如果您使用的是 VSCode,请尝试 Cmd + Shift + P 或 Ctrl + Shift + P 搜索Restart TS server
看用户输入错误是否还存在
{
"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,
},
}
https://stackoverflow.com/questions/67436289/