属性 `user` 在类型 `Session & Partial<SessionData>` 上不存在

Property `user` does not exist on type `Session & Partial<SessionData>`

我在 javascript 中有一个代码,我正在尝试将其转换为 typescript

route.get('/order', async(req,res) => {  
    var sessionData = req.session;
    if(typeof sessionData.user === 'undefined')
    {        
        res.redirect('/panel/login');
    }    

这是我的一段代码,曾经在 javascript 中正常工作,但现在我在 user:

中遇到此错误

Property 'user' does not exist on type 'Session & Partial'

我想我应该为 sessionData 变量和 (req, res) 参数添加类型,但我不知道应该为它分配什么类型。

PS:我知道这个问题看起来重复了,但我尝试了其他类似问题的解决方案,但没有用

如有任何帮助,我们将不胜感激。

我刚刚遇到了和你一样的问题。这似乎是一个相当新的问题:see explanation here.

为了解决这个问题,我按照 Github 问题中的描述重载了模块:

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

只需将 string 替换为该字段所需的任何类型即可。

另外我在tsconfig.json

中添加了./typing-stubs
"typeRoots": [
      "./typing-stubs",
      "./node_modules/@types"
]

express-session types comment所述,您必须使用Declaration merging

以下是在 express-session 上实施 Declaration merging 的方法:

import session from 'express-session';

declare module 'express-session' {
  export interface SessionData {
    user: { [key: string]: any };
  }
}

我最近遇到了这个问题,这是我想出的解决方案。

import { Request } from "express";
import { Session } from "express-session";

export type SessionWithUser = Session & { user: string | {}};

export type AuthRequest = Request & {
  session?: SessionWithUser;
  auth?: { user: string; permission_id: number };
};

这是为了将来参考,对于已经完成上述所有步骤但仍然失败的人(vscode不再显示错误但仍然失败),这可能是ts-node问题,将 --transpile-only 添加到您的 package.json 脚本中,如下所示:nodemon --exec ts-node -T src/app.ts.

来源:

追溯源码你会发现这样的评论:

    /**
     * This interface allows you to declare additional properties on your 
     * session object 
     * using [declaration merging] 
     * (https://www.typescriptlang.org/docs/handbook/declaration-merging.html).
     *
     * @example
     * declare module 'express-session' {
     *     interface SessionData {
     *         views: number;
     *     }
     * }
     *
     */
    interface SessionData {
        cookie: Cookie;
    }

继续阅读文档;你会发现一个模块扩充部分:https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation

现在,自己扩充“SessionData”并在其中添加“用户”:src/types/express-session/index。d.ts:

import { SessionData } from "express-session"

declare module "express-session" {
    interface SessionData {
        user: { [key: string]: any }
    }
}

您的 tsconfig.json 应该设置类型根以在您的编译中包含声明:

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