【问题标题】:JS/Docker - Property 'user' does not exist on type 'Session & Partial<SessionData>'JS/Docker - 'Session & Partial<SessionData>' 类型上不存在属性'user'
【发布时间】:2021-04-11 11:57:01
【问题描述】:

我正在尝试将express-session 添加到我在 Docker 下运行的 Node.js 应用程序中。

阅读很多帖子:

Express Session: Property 'signin' does not exist on type 'Session & Partial<SessionData>'. (2339) https://github.com/DefinitelyTyped/DefinitelyTyped/issues/49941 https://github.com/DefinitelyTyped/DefinitelyTyped/issues/46861

我尝试对Session 属性进行声明合并,这是我的tsconfig.json 的样子:

"typeRoots": [
  "./src/types",
  "./node_modules/@types"
]

在我的src/types 文件夹中,我有index.d.ts 文件:

declare module 'express-session' {
 interface Session {
    user: string;
  }
}

但是当我使用docker-compose up 命令运行我的项目时,它给了我以下错误:

/app/node_modules/ts-node/src/index.ts:421
     return new TSError(diagnosticText, diagnosticCodes)
            ^
 TSError: ⨯ Unable to compile TypeScript:
 src/routes/auth.ts(26,17): error TS2339: Property 'user' does not exist on type 'Session & Partial<SessionData>'.
 
     at createTSError (/app/node_modules/ts-node/src/index.ts:421:12

我认为这不是 Docker 问题,因为它发生在 Node.js 应用程序启动期间。 有谁知道如何解决这个问题?

【问题讨论】:

    标签: javascript node.js typescript docker express-session


    【解决方案1】:

    您应该扩展SessionData 接口,而不是Session@types/express-sessionindex.d.ts文件中没有Session接口。

    declare module 'express-session' {
      interface SessionData {
        user: string;
      }
    }
    

    【讨论】:

    • 我有同样的问题并尝试过,但 ts-node 仍然抛出错误。 tsc 和 ts-lint 接受声明,但由于某种原因 ts-node 不接受。
    【解决方案2】:

    除了上一个答案,您必须扩展SessionData 接口,您可以使用--files 标志ts-node。 在这个答案post 中描述。现在看来ts-node 不接受你的tsconfig.json

    【讨论】:

      【解决方案3】:

      要扩展express-session 类型(截至@types/express-session@^1.17.4),您需要添加:

      import "express-session"
      

      到您的d.ts 文件的顶部:即:

      import "express-session"; 
      
      declare module 'express-session' {
        interface SessionData {
          tenant: string
        }
      }
      

      还要确保,正如@slideshowp2 所说,您正在扩展SessionData 不是 Session

      【讨论】:

        猜你喜欢
        • 2021-03-14
        • 2021-04-14
        • 2021-03-15
        • 2018-07-30
        • 2022-09-23
        • 1970-01-01
        • 2018-01-29
        • 2020-08-23
        • 2021-11-04
        相关资源
        最近更新 更多