无法覆盖快速请求用户类型,但我可以向请求添加新属性

Dav*_*vid 0 express typescript

这是一个看似常见解决方案的典型问题。Express Request 对象有一个名为 user 的属性,其类型为 Express.User(空对象)。

我尝试使用常见的解决方案来重新输入它:

// index.d.ts

import { User as PrismaUser, Profile } from "@prisma/client";

declare global {
  namespace Express {
    export interface Request {
      user: PrismaUser & { profile: Profile };
    }
  }
}

Run Code Online (Sandbox Code Playgroud)

该文件被我的tsconfig.json文件捕获。

当我执行上述操作时,出现以下错误:

所有“user”声明必须具有相同的修饰符。ts(2687)

后续的属性声明必须具有相同的类型。属性“user”必须是“User”类型,但这里的类型是“User & { profile: Profile; }'。

本质上,我被告知它必须键入为 Express.User。

同时,做好以下工作:

declare global {
  namespace Express {
    export interface Request {
      currentUser: PrismaUser & { profile: Profile };
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我可以在我的代码中使用request.currentUser

为什么我不能更改用户属性的类型,就像我在这里看到的许多其他答案一样?我没有看到其他人遇到我的错误。也许我的 tsconfig 坏了?

Dav*_*vid 7

我的想法全错了。

@types/passport 添加了一个 Express.User 到 Express 并使 Express.Request.User 成为 Express.User 类型...

我必须做的是以下

import { User, Profile } from "@prisma/client";

type ProductUser = User & { profile: Profile };

declare global {
  namespace Express {
    interface User extends ProductUser {}
  }
}
Run Code Online (Sandbox Code Playgroud)

这避免了尝试对已合并的属性使用声明合并,这给了我遇到的错误。