NestJS TypeScript含相同属性类继承报错求助
问题原因
TypeScript 中父类的 private 私有属性仅能在父类内部访问,子类既无法继承该属性,也不能重复声明同名的私有属性,这就是你遇到错误的核心原因。
解决方法
以下两种方案均可解决该问题,可根据实际需求选择:
方案一:将父类属性改为 protected(推荐)
把父类的 userService 访问修饰符改为 protected,这样子类可以继承并访问该属性,无需重复声明:
import { Inject, Injectable, UnauthorizedException } from "@nestjs/common"; export interface IUser { id: string; name: string; email: string; password: string; } export interface IUserService { findById(id: string): Promise<IUser | null>; findByEmail(email: string): Promise<IUser | null>; verifyPassword(user: IUser, password: string): Promise<Boolean>; } @Injectable() export abstract class AuthService { constructor(protected userService: IUserService) {} async loginWithEmail(email: string, password: string) { const user = await this.userService.findByEmail(email); // 新增用户不存在的判断,避免空指针报错 if (!user || user.password !== password) { throw new UnauthorizedException('Invalid email & password!'); } return user; } } export class UserAuthService extends AuthService { constructor(@Inject('user-service-token') userService: IUserService) { super(userService); } }
方案二:子类不重复声明属性(父类保持 private)
如果父类的 userService 必须保持私有,子类只需在构造函数中注入依赖并传递给父类,无需重复声明该属性(注意:这种方式子类无法直接访问 userService):
import { Inject, Injectable, UnauthorizedException } from "@nestjs/common"; // 接口定义部分不变 @Injectable() export abstract class AuthService { constructor(private userService: IUserService) {} async loginWithEmail(email: string, password: string) { const user = await this.userService.findByEmail(email); if (!user || user.password !== password) { throw new UnauthorizedException('Invalid email & password!'); } return user; } } export class UserAuthService extends AuthService { constructor(@Inject('user-service-token') userService: IUserService) { super(userService); } }
内容的提问来源于stack exchange,提问作者Rohit Khatri
相关产品推荐
相关产品推荐

