【问题标题】:Adding additional properties to session object向会话对象添加附加属性
【发布时间】:2021-07-14 09:24:24
【问题描述】:

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

req.session.confirmationCode = confirmationCode;

但收到确认代码属性不存在的错误

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

我在添加此道具的 types 目录下有 index.d.ts 文件

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 包的源代码中看到我可以像这样扩展会话对象

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

但是当我这样做时,我收到一个错误,即会话函数不可调用

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

如何正确扩展会话对象?

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

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",
    },
  })
);

【问题讨论】:

  • 你是如何导入express-session包的?
  • @slideshowp2 像往常一样 import session from "express-session"; 我还在 tsconfig.json 中添加了 allowSyntheticDefaultImports 属性

标签: typescript express express-session


【解决方案1】:

我在question 中找到了答案。

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

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

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

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

export {};

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多