使用 ts-node 时,Typescript 的声明合并无法按预期工作

2024-05-01

对于使用的项目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,使用同一文件夹。


最新更新(2021 年 5 月 8 日)

使用以下命令运行打字稿程序时ts-node, even typeRoots在 tsconfig.json 中指定,无法识别自定义 .d.ts 并提示Property 'x类型 y` 错误不存在。

根据https://github.com/TypeStrong/ts-node/issues/1132#issuecomment-716642560 https://github.com/TypeStrong/ts-node/issues/1132#issuecomment-716642560

贡献者之一ts-node提出了多种解决方法。

这是其中之一: 指定file: true标记在tsconfig.json通知ts-node加载files, include and exclude选项来自tsconfig.json启动时

{
  "ts-node": {
    "files": true
  },
  "exclude": [...],
  "compilerOptions": {
   ...
}

旧版:(2021 年 5 月 7 日)

没有必要使用include in tsconfig.json并且路径不正确。编译器可以在目录及子目录中搜索ts文件

尝试将其删除。并重新启动 TS 服务器。

If you are using VSCode, try Cmd + Shift + P or Ctrl + Shift + P and search Restart TS server and see if the user type error still exist

{
    "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,
    },
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 ts-node 时,Typescript 的声明合并无法按预期工作 的相关文章

随机推荐