TypeScript 프로젝트에 strictNullChecks 적용하기
배경
회사 프로젝트가 TypeScript로 마이그레이션된 지 6개월이 지났다. 하지만 tsconfig.json에서 strictNullChecks를 활성화하지 않은 상태로 개발하다 보니, 런타임에 Cannot read property of undefined 에러가 자주 발생했다.
이번 스프린트에서 시간을 할애받아 strictNullChecks를 적용하기로 했다.
문제 상황
strictNullChecks: true로 설정하자마자 800개가 넘는 타입 에러가 발생했다. 한 번에 모두 수정하는 것은 불가능했다.
// 기존 코드
function getUserName(user: User) {
return user.profile.name; // profile이 undefined일 수 있음
}
const items = data.filter(item => item.active);
const firstItem = items[0]; // undefined 가능성
해결 과정
1. 모듈 단위 적용
전체를 한 번에 수정하는 대신, 파일 상단에 주석으로 strict 체크를 활성화하는 방식을 택했다.
// @ts-check
// tsconfig.json에서는 아직 false로 유지
2. Optional Chaining 대안
TypeScript 3.7에서 Optional Chaining이 추가될 예정이지만, 현재는 2.9를 사용 중이다. 명시적 체크로 대응했다.
function getUserName(user: User) {
if (!user.profile) return 'Unknown';
return user.profile.name;
}
// 또는 타입 가드
function hasProfile(user: User): user is User & { profile: Profile } {
return user.profile !== undefined;
}
3. 배열 접근 처리
const firstItem = items[0]; // string | undefined
if (firstItem) {
console.log(firstItem.toUpperCase());
}
// 또는 기본값 제공
const firstItem = items[0] || 'default';
결과
2주간 핵심 모듈 20개 파일에 strict 체크를 적용했다. 실제로 잠재적 버그 3건을 사전에 발견했다.
다음 분기에는 전체 프로젝트에 strictNullChecks를 활성화할 계획이다.