[英]What is wrong with Inheritance in Typescript?
Typescript 中的 inheritance 有什么問題?
我創建了這個 class:
export class ExtendedService<T extends ExtendedEntity> {
protected repository: Repository<T>;
constructor(
repository?: Repository<T>
){
this.repository = repository;
}
public async create(data: DeepPartial<T>): Promise<T> {
const entity: T = this.repository.create(data);
return entity.save();
}
}
並在此擴展此 class :
@Injectable()
export class UserService extends ExtendedService<UserEntity> {
constructor(
protected readonly repository: Repository<UserEntity>
){
super();
}
public async register(data: DeepPartial<UserEntity>): Promise<UserEntity> {
const user = new UserEntity();
user.createdAt = new Date();
user.firstName = data.firstName;
user.lastName = data.lastName;
user.email = data.email;
user.role = UserRole.USER;
user.isDeleted = false;
const salt = await genSalt(10);
user.password = await hash(data.password, salt);
return await this.create(user);
}
}
但是在啟動這個 function 之后,我的控制台向我拋出了這個:
[Nest] 19980 - 2020-06-29 17:30:56 [ExceptionsHandler] Cannot read property 'create' of undefined +1378ms
TypeError: Cannot read property 'create' of undefined
at Repository.create (C:\Users\Piotruś\Desktop\auth\node_modules\typeorm\repository\Repository.js:49:29)
at UserService.create (C:\Users\Piotruś\Desktop\auth\dist\helpers\service\extended-service.js:27:40)
at UserService.register (C:\Users\Piotruś\Desktop\auth\dist\user\user.service.js:34:27)
at async UserController.register (C:\Users\Piotruś\Desktop\auth\dist\user\user.controller.js:25:9)
at async C:\Users\Piotruś\Desktop\auth\node_modules\@nestjs\core\router\router-execution-context.js:46:28
at async C:\Users\Piotruś\Desktop\auth\node_modules\@nestjs\core\router\router-proxy.js:9:17
所以,問題出在 ts inheritance 中,誰能告訴我我的 inheritance 出了什么問題?
您沒有將repository
參數傳遞給您的基礎 class。 在構造函數中調用super()
時,必須提供所有基本 class arguments。
@Injectable()
export class UserService extends ExtendedService<UserEntity> {
constructor(
protected readonly repository: Repository<UserEntity>
){
super(repository);
}
...
}
正如您在此娛樂中看到的那樣,將基類存儲庫參數設為強制性會導致 Typescript 引發編譯錯誤:
預期為 1 arguments,但得到 0。
除非必要,否則我建議您避免將 arguments 設為可選,如果這樣做,請采取預防措施以進行必要的 null 檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.