TypeScript 3.7 Optional Chaining으로 null 체크 지옥 탈출

문제 상황

외부 API 응답을 처리하는 코드에서 중첩된 객체 접근이 많았다. 매번 null/undefined 체크를 하다 보니 코드가 지저분해졌다.

// 기존 코드
const city = user && user.address && user.address.city;
const firstPostTitle = user && user.posts && user.posts[0] && user.posts[0].title;

Optional Chaining 적용

TypeScript 3.7에서 Optional Chaining(?.)이 정식 지원되면서 코드가 훨씬 깔끔해졌다.

// 개선된 코드
const city = user?.address?.city;
const firstPostTitle = user?.posts?.[0]?.title;

Nullish Coalescing과 함께 사용

?? 연산자와 조합하면 기본값 처리도 간결해진다.

const displayName = user?.profile?.name ?? 'Anonymous';
const postCount = user?.posts?.length ?? 0;

주의할 점

  • 바벨 설정에서 @babel/plugin-proposal-optional-chaining 필요
  • 타겟 브라우저가 ES2020 미만이면 폴리필 고려
  • Optional Chaining은 단락 평가되므로 우측 표현식이 실행되지 않을 수 있음
// onLoad는 user가 없으면 호출되지 않음
user?.profile?.load?.(onLoad());

결론

프로젝트 전반에 적용했더니 null 체크 관련 코드가 30% 가량 줄었다. tsconfig의 target을 ES2019로 설정하고 바벨로 트랜스파일하는 방식으로 운영 환경에 배포했다.

TypeScript 3.7 Optional Chaining으로 null 체크 지옥 탈출