向会话对象添加额外的属性

Adding additional properties to session object

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

req.session.confirmationCode = confirmationCode;

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

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

我在类型目录下有 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",
    },
  })
);

我在这个 中找到了答案。

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

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

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

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

export {};

node_modules > @types > express-session > index.d.ts里面,我发现Session的定义如下。 (我删除了所有评论)

class Session {
  private constructor(request: Express.Request, data: SessionData);
  id: string;
  cookie: Cookie;
  regenerate(callback: (err: any) => void): this;
  destroy(callback: (err: any) => void): this;
  reload(callback: (err: any) => void): this;
    @see Cookie
  resetMaxAge(): this;
  save(callback?: (err: any) => void): this;
  touch(): this;
}

我刚刚在会话中添加了我想要的 属性,userId

现在我的 node_modules > @types > express-session > index.d.ts 看起来像:

class Session {
  private constructor(request: Express.Request, data: SessionData);
  id: string;
  userId: number; // This is the property I added.
  cookie: Cookie;
  regenerate(callback: (err: any) => void): this;
  destroy(callback: (err: any) => void): this;
  reload(callback: (err: any) => void): this;
    @see Cookie
  resetMaxAge(): this;
  save(callback?: (err: any) => void): this;
  touch(): this;
}

我不确定这是否是最好的方法,但它对我有用。