예시

@Entity()
export class Exercise extends Timestamps {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: 'enum', enum: BodyPart })
  bodyPart: BodyPart;

  @Column()
  exerciseName: string;

  @OneToMany(() => WorkoutLog, (workoutLog) => workoutLog.exercise)
  workoutLogs: WorkoutLog[];

  @OneToMany(() => RoutineToExercise, (routineToExercise) => routineToExercise.exercise)
  routineToExercises: RoutineToExercise[];

  constructor();
  constructor(params: { bodyPart: BodyPart; exerciseName: string });
  constructor(params?: { bodyPart: BodyPart; exerciseName: string }) {
    super();
    if (params) {
      this.exerciseName = params.exerciseName;
      this.bodyPart = params.bodyPart;
    }
  }
}

  constructor :  클래스에서 객체의 설계도 또는 청사진으로, 특정 타입의 객체를 생성하고 초기화하는데 사용됩니다.

  • constructor() 초기화할 속성이 없는 경우에 사용
  • constructor(params? : {})  매개변수가 선택적이라는 의미 (optional)
  • constructor(params : {}) 매개변수가 선택적이라는 의미 (optional)

위 코드에서 매개변수의 초기화가 꼭 필요하기 때문에 

constructor() 와 constructor(params? : {}) 는 필요없는 코드

 

  .....
  // 이 와 같이 수정
  constructor(params: { bodyPart: BodyPart; exerciseName: string }){
    super();
    if (params) {
      this.exerciseName = params.exerciseName;
      this.bodyPart = params.bodyPart;
    }
  }

constructor(params:{}) 에서 params를 선언했는데  왜 if(params) 가 필요할까??

( TypeORM 공식문서에서 보면)

When using an entity constructor its arguments must be optional. Since ORM creates instances of entity classes when loading from the database, therefore it is not aware of your constructor arguments.

 

ORM 은 앱을 실행시킬때 엔티티의 인스턴스를 생성한다. 그러면 초기화 값을 받지 못한 params 는 undefined 가 되어 버리기 때문에 앱 실행 중에 오류가 발생한다.

 

 

 

참고자료

TypeORM 공식문서

https://seungtaek-overflow.tistory.com/15

+ Recent posts