본문 바로가기

개발/개발의 ㄱ

[NestJs] DTO 유효성 vs constructor 초기화 (when strict mode)

반응형

controller에서 파라미터(query, param, body) 유효성을 검사하기 위해 DTO를 사용한다.

그런데 코드 품질?을 위해 tsconfig.json에서 "strict: true" 설정을 하면, class 프로퍼티(state)들은 초기화하라고 아래 문구가 뜬다.

has no initializer and is not definitely assigned in the constructor

재밌는건 초기화 하면, client 값이 아닌 계속해서 초기화 값을 출력한다는.......

고민한 끝에, 아래 두가지 방법을 제안한다.

 

 

1) "strictPropertyInitialization": false

tsconfig.json에 "strictPropertyInitialization": false을 추가한다.

{
  "compilerOptions": {
    "strict": true,
    "strictPropertyInitialization": false,
  ...
  }
}

property 초기화를 강제하지 않아도 되는데, 다른 class에서도 안하게 되니..... 염려되는 부분이 있다.

 

2) Definite Assignment Assertions

Definite Assignment Assertions(확정 할당 어선셜)을 위해 프로퍼티 끝에 !를 붙인다.

이 값은 무조건 올거야 뉘앙스로, 초기화하지 않을수 있습니다. 그리고 다른 class 초기화에 영향을 주지 않는다.

class Class {
	state!: string
}

 

 

필자의 경우 유효성 검증과 다른 class 초기화에 영향을 주지 않는다는 점에서 DAA를 사용했다.

*다른 분들의 의견도 공유해주면 좋겠습니다

*코드 깨지면 아래 링크 참조해주세요

 

https://medium.com/%EB%8F%84%EA%B9%A8%EB%B9%84-%EC%9D%B4%EC%95%BC%EA%B8%B0/nestjs-dto-%EC%9C%A0%ED%9A%A8%EC%84%B1-vs-constructor-%EC%B4%88%EA%B8%B0%ED%99%94-when-strict-mode-58fbcd2fb652