TypeScript 5.6 Beta의 Nullish와 Truthy 체크 개선

배경

프로젝트에서 Optional 값 처리 시 타입 가드를 많이 사용하고 있었는데, TypeScript 5.6 베타에서 null/undefined 체크가 개선되었다는 소식을 듣고 적용해봤다.

기존 문제점

function processValue(value: string | null | undefined) {
  const result = value || 'default';
  // result는 여전히 string | null | undefined로 추론됨
  return result.toUpperCase(); // 에러 발생
}

기존에는 || 연산자를 사용해도 타입이 제대로 좁혀지지 않아 별도의 타입 단언이나 가드가 필요했다.

5.6에서의 개선

function processValue(value: string | null | undefined) {
  const result = value ?? 'default';
  // result는 이제 string으로 정확히 추론됨
  return result.toUpperCase(); // OK
}

function checkTruthy(value: string | null | 0 | false) {
  if (value) {
    // value는 string으로 좁혀짐
    console.log(value.length);
  }
}

?? 연산자와 truthy 체크에서 타입 좁히기가 훨씬 정교해졌다.

실무 적용

API 응답 처리 코드를 리팩토링했다.

interface ApiResponse {
  data?: { name: string; age: number } | null;
}

function handleResponse(response: ApiResponse) {
  const data = response.data ?? { name: 'Unknown', age: 0 };
  // 이제 data는 명확히 { name: string; age: number } 타입
  console.log(data.name, data.age);
}

불필요한 타입 단언을 제거하고 코드가 더 간결해졌다.

정리

타입 추론 개선으로 보일러플레이트가 줄어들고 런타임 안정성도 높아졌다. 아직 베타 단계지만 안정화되면 프로젝트 전반에 적용할 계획이다.