命名空间 'Express' 没有导出成员 'SessionData'

Namespace 'Express' has no exported member 'SessionData'

我正在尝试构建一个 typeScript 项目,但它有一个错误,我不知道它来自哪里,自上次以来没有任何改变。


node_modules/connect-mongo/src/types.d.ts:113:66 - error TS2694: Namespace 'Express' has no exported member 'SessionData'.

113         get: (sid: string, callback: (err: any, session: Express.SessionData | null) => void) => void;
                                                                     ~~~~~~~~~~~

node_modules/connect-mongo/src/types.d.ts:114:45 - error TS2694: Namespace 'Express' has no exported member 'SessionData'.

114         set: (sid: string, session: Express.SessionData, callback?: (err: any) => void) => void;
                                                ~~~~~~~~~~~

node_modules/connect-mongo/src/types.d.ts:118:47 - error TS2694: Namespace 'Express' has no exported member 'SessionData'.

118         touch: (sid: string, session: Express.SessionData, callback?: (err: any) => void) => void;
                                                  ~~~~~~~~~~~

src/controllers/http/auth/auth.ts:16:44 - error TS2339: Property 'user' does not exist on type 'Session & Partial<SessionData>'.

16             if (req.session && req.session.user) {
                                              ~~~~

src/controllers/http/auth/auth.ts:41:29 - error TS2339: Property 'user' does not exist on type 'Session & Partial<SessionData>'.

41                 req.session.user = user;
                               ~~~~

The place where the typescript gives an error

express-session this is how it is imported

对于 connect-mongo 库类型检查,尝试将 skipLibCheck 选项添加到您的 tsconfig.json

{
  "compilerOptions": {
    ....
    "skipLibCheck": true
  }
}

对于行内代码,尝试添加// @ts-ignore

// @ts-ignore
req.session.user = user;

请注意,这只是一种解决方法,今天我在不更改任何代码的情况下尝试在 DockerHub 上重建 docker 映像时遇到了同样的问题。

我恢复到这个版本来解决这个问题: "@types/express-session": "1.15.16",

看来 SessionData 接口已从全局 Express 命名空间中删除,在 10 月 13 日的第 24 行,最近发布在相应的 DefinitelyTyped 模块中 -

https://github.com/HoldYourWaffle/DefinitelyTyped/commit/0cec4865fe7fd873952fc6901553a96648a7c889#diff-c38f30a0fdd238f104a7392ff3881fa97d8b4497d75e9617163ac1b5fceb75bf

这里有很多讨论 - https://github.com/DefinitelyTyped/DefinitelyTyped/pull/46576

我怀疑这最终会在某些时候在 connect-mongo 代码中更新,但与此同时,您可以使用 @benhu 提到的 skipLibCheck 标志来解决它,或者,如果你想为其他库保留该功能,你可以在你自己的代码中的某个地方添加接口,如下所示:

// WORKAROUND TODO: Remove when the connect-mongo types are updated
declare global {
  namespace Express {
    interface SessionData {
      cookie: any
    }
  }
}