[英]Typescript's declaration merging not working as expected using ts-node
對於使用express-session
package 的項目,我試圖通過簡單地添加用戶密鑰來改變session
object。
req.session.user = 123;
來自這個問題的接受答案,我知道我可以使用聲明合並來擴展SessionData
接口,使用我自己的接口。
查看各種開源項目,例如HospitalRun 組件存儲庫,我注意到它們在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 object 的代碼上方添加這段代碼時,我不再遇到問題。 不過,這似乎不是正確的方法。
此外,當我使用tsc src/index.ts --build
而不是ts-node src/index.ts
它也可以工作。
我在這里做錯了什么? 如何解決這個問題? 我也嘗試使用typeRoots
,使用相同的文件夾。
最新更新(2021 年 5 月 8 日)
使用ts-node
運行 typescript 程序時,即使在typeRoots
中指定了 typeRoots,它也無法識別 custom.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
,在啟動時從tsconfig.json
中include
和exclude
選項
{
"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,
},
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.