admin管理员组文章数量:1287200
I'm trying to follow best practices by keeping my entity properties private and accessing them via getters and setters, but I run into a compile-time issue when referencing private properties in TypeORM relationship decorators.
For example, I have the following entity:
import {
Column,
CreateDateColumn,
Entity,
ManyToOne,
PrimaryGeneratedColumn,
} from "typeorm";
import { UserEntity } from "../../auth/models/user.entity";
@Entity("product")
export class ProductEntity {
@PrimaryGeneratedColumn()
private id: number;
@Column({ default: "" })
private body: string;
@CreateDateColumn()
private createdAt: Date;
@ManyToOne(() => UserEntity, user => user.products)
private _creator: UserEntity;
public get creator(): UserEntity {
return this._creator;
}
public set creator(value: UserEntity) {
this._creator = value;
}
}
And the corresponding inverse side in UserEntity:
import { Entity, OneToMany } from "typeorm";
import { ProductEntity } from "./product.entity";
@Entity("user")
export class UserEntity {
@OneToMany(() => ProductEntity, product => product.creator)
private _products: ProductEntity[];
public get products(): ProductEntity[] {
return this._products;
}
}
However, TypeScript complains because the lambda in the relationship decorator on UserEntity (or ProductEntity) is trying to access a private property. I understand that TypeORM uses runtime reflection, so the private modifier doesn't affect the ORM functionality, but it does cause issues at compile time.
One workaround mentioned is to use bracket notation like userEntity["_products"] to bypass TypeScript's access restrictions. Is this an acceptable practice, or is there a better alternative to maintain encapsulation without causing compile-time errors?
Any insights or recommendations would be appreciated. Thanks in advance!
本文标签:
版权声明:本文标题:typescript - How can I reference private properties in TypeORM relationship decorators while keeping encapsulation? - Stack Over 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741261212a2367657.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论