Estoy utilizando express
y passport
en mi aplicación. En ambos paquetes, hay un atributo de user
en la interfaz de Request
. Actualmente, express
tiene un atributo de user
pero no tiene otras propiedades adjuntas en el objeto de solicitud, por ejemplo, req.user
. Estoy tratando de hacer una combinación de declaración (no estoy realmente seguro de si este es el término correcto para ello) para express para decirle a mecanografiado que Express.Request.user
tiene un atributo de id
adjunto de la siguiente manera:
declare namespace Express { export interface Request { user: { id: string } } }
Al mismo tiempo, el passport
también tiene un atributo de user
pero con el valor de Express.User
. Cuando realizo la combinación de declaraciones anterior, aparece un error que dice All declarations of 'user' must have identical modifiers.
Aquí está el archivo de declaración de passport
.
interface User {} interface Request { authInfo?: AuthInfo; user?: User; // These declarations are merged into express's Request type login(user: User, done: (err: any) => void): void; login(user: User, options: any, done: (err: any) => void): void; logIn(user: User, done: (err: any) => void): void; logIn(user: User, options: any, done: (err: any) => void): void; logout(): void; logOut(): void; isAuthenticated(): this is AuthenticatedRequest; isUnauthenticated(): this is UnauthenticatedRequest; }
Entiendo que se debe a una falta de coincidencia en las interfaces, pero ¿cómo supero esto? Cualquier ayuda es bienvenida. ¡Muchos gracias!
Tuve el mismo problema: logré que funcionara agregando propiedades directamente a la interfaz de User
en lugar de Request.user
.
En @types/express/index.d.ts
declare global { namespace Express { interface User { userId: number; name: string; email: string; } } }
Tuve el mismo problema y también luché por una tarde. Me las arreglé para que funcione así en mi proyecto:
declare global { namespace Express { interface User extends UserDocument { // A basic field so EsLint does not think it's an empty interface, // and replace it with some other code which it thinks to be better // (cause for me, it was replacing automatically the line with // "type User = UserDocument" which was making Typescript unhappy). // This field is useless, but that's the only solution I found. uselessField?: boolean; } } } // Alternatively, you can also substitute this line declaration with: // "export type UserD = mongoose.Document & {" // as seen in the Microsoft starter template: https://github.com/microsoft/TypeScript-Node-Starter // It works too. export interface UserDocument extends mongoose.Document { firstName: string; lastName: string; email: string; // ... etc } const UserSchema = new mongoose.Schema<UserDocument>( { firstName: String; lastName: String; email: String; // ... etc }, ); export const User = mongoose.model<UserDocument>("User", UserSchema);