【问题标题】:Typescript Declaration Merging Express Request Object and Passport.js User/SessionTypescript 声明合并 Express 请求对象和 Passport.js 用户/会话
【发布时间】:2021-07-08 15:42:19
【问题描述】:

我在 express/nodejs 应用程序中使用 passportjs 中间件进行身份验证。尽管遵循了Declaration Merging 的步骤,但我的 request.user 对象的属性出现错误。

我在项目根目录的 /types/index.d.ts 创建了一个文件,并将以下内容添加到我的 tsconfig.json 中

"typeRoots": [
  "/types/index.ts", "node_modules/@types"
]

我的全局声明合并如下所示:

import { User } from "../users/user.interface";
declare global {
  namespace Express {
    export interface Request {
        user: User;
    }
  }
}

** 更新 ** 我已经得到了req.user 对象,通过将我的声明合并更改为模块增强来停止抛出错误,如下所示:

import { User } from "../users/user.interface";

declare module "express-serve-static-core" {
    interface Request {
        user: User;
    }
}

当引用 request.session 对象时,我收到以下错误:Property 'session' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

passport 的 @types/passport 类型不应该与 express 的请求对象合并以添加会话吗?

有谁知道我如何成功消除这些错误/让 TS 识别此声明合并。我是 typescript 的新手,已经能够解决我遇到的大部分问题,但这个问题一直在浮出水面。

【问题讨论】:

    标签: typescript express types passport.js typescript-typings


    【解决方案1】:

    要扩展 Passport 使用的 User 类型,您可以将声明合并到 global.Express.User

    declare global {
      namespace Express {
        interface User {
            /* declare your properties here */
        }
      }
    }
    

    @types/passport 提供的类型定义没有定义global.Express.Request#session,即由@types/express-session here 定义。

    【讨论】:

    • 谢谢@samthecodingman,我重新安装了@types/express-session 包并更改了导入,这似乎已被清除。我已经像您在此处发布的那样宣布了合并,但这没有用。将其声明为“express-serve-static-core”的模块增强确实有效。
    猜你喜欢
    • 2020-11-05
    • 2018-05-22
    • 1970-01-01
    • 2020-11-15
    • 2021-03-24
    • 2017-08-05
    • 2010-10-14
    • 2021-06-05
    • 1970-01-01
    相关资源
    最近更新 更多