繁体   English   中英

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

[英]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.jsonincludeexclude选项

{
  "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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM