typescript - 向 session 对象添加附加属性

标签 typescript express express-session

我正在尝试向 session 对象添加其他属性

req.session.confirmationCode = confirmationCode;

但是收到一个错误,确认Code属性不存在

Property 'confirmationCode' does not exist on type 'Session & Partial<SessionData>'.

我在 types 目录下有 index.d.ts 文件,我在其中添加此 Prop

declare global {
  namespace session {
    interface SessionData {
      confirmationCode: number;
    }
  }
}

export {};

这是我的 tsconfig.json 文件

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "lib": ["dom", "es6", "es2017", "esnext.asynciterable"],
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
    "removeComments": true,
    "strict": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "noImplicitAny": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noStrictGenericChecks": true
  },
  "exclude": ["node_modules"],
  "include": ["src"]
}

我在 @types/express-session 包的源代码中看到我可以扩展 session 对象,例如

declare module "express-session" {
  interface SessionData {
    confirmationCode: number;
  }
}

但是当我这样做时,我收到一个错误,表明 session 函数不可调用

Type 'typeof import("express-session")' has no call signatures

如何正确扩展 session 对象?

UPD1:这就是我调用 session 函数的方式

app.use(
  session({
    name: "wishlify",
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: {
      maxAge: 1000 * 60 * 60 * 24 * 60, // 2 months
      secure: process.env.NODE_ENV === "production",
    },
  })
);

最佳答案

我在这个question中找到了答案.

我将 export {}; 添加到了 index.d.ts 文件,现在可以按预期工作。

这一行使得文件不是一个脚本而是一个模块。

index.d.ts 文件的最终版本

declare module "express-session" {
  interface SessionData {
    confirmationCode: number;
  }
}

export {};

关于typescript - 向 session 对象添加附加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67174560/

相关文章:

javascript - Express 路由正则表达式生成的意外行为

node.js - 每次重新加载 session 都会重置 NodeJS/将创建一个新 session

ios - Podfile.lock没有这样的文件或目录

arrays - 如何将数组中对象的属性分配给多个类属性?

javascript - 使用 Mongoose 和 Node/ express 保存新帖子时遇到问题

node.js - 快速 session :捆绑内存存储的替代方案

node.js - nodejs - heroku - 快速 session

Angular 类型错误 : is not a function when trying to call an object. 对象 []. 方法

typescript - ‘serviceBusTrigger’, 'signalR' 绑定(bind)类型突然未注册

node.js - Express 静态中间件在日志中返回错误