TypeScript 4.6의 Control Flow Analysis 개선 사항

문제 상황

프로젝트에서 API 응답을 처리하는 코드를 작성하다가 타입 narrowing이 제대로 동작하지 않는 상황을 자주 마주쳤다.

interface User {
  id: string;
  name: string;
}

interface ApiResponse {
  data?: User;
  error?: string;
}

function handleResponse(response: ApiResponse) {
  const { data, error } = response;
  
  if (error) {
    console.error(error);
    return;
  }
  
  // TypeScript 4.5에서는 여전히 data가 undefined일 수 있다고 판단
  console.log(data.name); // Error: Object is possibly 'undefined'
}

이런 경우 data!.name으로 타입 단언을 하거나, destructuring 없이 response.data로 접근해야 했다.

TypeScript 4.6 개선

TypeScript 4.6부터는 destructured 변수에 대해서도 control flow analysis가 정상적으로 동작한다. discriminated union과 조합하면 더욱 강력하다.

type Result<T> = 
  | { success: true; data: T }
  | { success: false; error: string };

function process(result: Result<User>) {
  const { success } = result;
  
  if (!success) {
    console.error(result.error); // 정상 동작
    return;
  }
  
  console.log(result.data.name); // 타입 에러 없음
}

실무 적용

레거시 코드에서 타입 단언을 제거하고 더 안전한 코드로 개선할 수 있었다. 특히 Redux reducer나 API 클라이언트 코드에서 효과가 컸다.

다만 아직 베타 단계이므로 팀 내에서는 4.6 정식 릴리즈 후 적용하기로 결정했다. 현재는 개인 사이드 프로젝트에서 테스트 중이다.

TypeScript 4.6의 Control Flow Analysis 개선 사항