구별된 공용체를 사용한 유형 안전 상태 전환구별된 공용체를 사용한 유형 안전 상태 전환

구별된 공용체를 사용한 유형 안전 상태 전환

통합 필드(예: '상태' 태그)를 활용하여 비즈니스 조건을 명확하게 구분하고 TS 완전성 확인을 허용합니다.

TypeScript를 사용한 최신 프런트엔드 및 백엔드 개발에서 상태 전환 중 유형 안전성을 보장하는 것은 강력하고 충돌 없는 애플리케이션을 구축하는 데 중요한 요소입니다. 비동기 API 통신(예: 로드, 성공 및 오류 상태 간 전환) 또는 복잡한 사용자 상호 작용을 처리할 때 모호한 유형 정의로 인해 예상치 못한 런타임 오류가 쉽게 발생할 수 있습니다.

이 기사에서는 TypeScript에서 Discriminated Unions(Tagged Unions라고도 함)의 기능을 활용하여 최소한의 상용구를 사용하여 상태를 안전하고 우아하게 관리하는 방법을 살펴보겠습니다.


1. 차별적 노동조합이란 무엇입니까?

구별된 공용체는 여러 고유 개체 유형을 단일 공용체 유형(|)으로 결합하는 TypeScript의 패턴입니다. 여기서 각 개체 유형은 “판별” 또는 “태그"라고 하는 공통 리터럴 속성을 공유합니다.

TypeScript의 컴파일러는 조건부 구조(예: if 또는 switch 문) 내에서 이 태그를 읽어 해당 블록 내에서 객체 유형의 범위를 자동으로 좁힐 수 있습니다(유형 축소라고 함).

차별적 결합의 핵심 요소:

  1. 여러 개체 유형이 하나의 통합체로 결합되었습니다.
  2. 모든 유형에 존재하는 공유 속성 이름(판별자).
  3. 이 공유 속성의 유형은 리터럴 유형(특정 문자열, 숫자 또는 부울)입니다.

2. 순진한 접근 방식: 단일 모놀리식 객체

Discriminate Union에 대해 알아보기 전에 모든 선택적 필드를 포함하는 단일 개체 표현을 사용하는 안티 패턴을 살펴보겠습니다.

// Anti-pattern: Optional properties for all possible states
interface FetchState<T> {
 isLoading: boolean;
 data?: T;
 error?: Error;
}

function renderState<T>(state: FetchState<T>) {
 if (state.isLoading) {
 return "Loading...";
 }

 // Even if isLoading is false, there is no guarantee that data or error is present.
 if (state.data) {
 // TypeScript requires a check or safe-navigation because 'data' is optional.
 return `Data: ${JSON.stringify(state.data)}`;
 }

 if (state.error) {
 return `Error: ${state.error.message}`;
 }

 return "Unknown state";
}

이 접근 방식의 단점:

  • 불가능한 상태를 쉽게 구성할 수 있습니다(예: ‘data’와 ’error’가 동시에 정의되거나 ‘isLoading’이 false인 경우 둘 다 ‘undefine’됨).
  • 개발자는 데이터에 액세스하기 위해 선택적 연결(?.) 또는 null이 아닌 어설션 연산자(!)를 지속적으로 사용해야 합니다. 이는 정적 유형 검사의 목적을 훼손합니다.

3. 차별적인 Union 구현하기

Union 유형을 통해 결합된 엄격하게 정의된 상태 집합을 사용하여 상태 표현을 다시 디자인해 보겠습니다.

// Define separate interfaces for every distinct status
interface IdleState {
 type: 'idle';
}

interface LoadingState {
 type: 'loading';
}

interface SuccessState<T> {
 type: 'success';
 data: T;
}

interface ErrorState {
 type: 'error';
 error: Error;
}

// Combine them into a union type
type FetchState<T> = IdleState | LoadingState | SuccessState<T> | ErrorState;

이 모델에서는 type 속성이 판별 기준입니다. 이제 이 상태를 렌더링하는 것이 얼마나 쉬운지 살펴보겠습니다.

function renderState<T>(state: FetchState<T>): string {
 switch (state.type) {
 case 'idle':
 return 'Waiting...';
 case 'loading':
 return 'Loading...';
 case 'success':
 // compiler guarantees that 'data' is present here. No optional chaining needed.
 return `Data: ${JSON.stringify(state.data)}`;
 case 'error':
 // compiler guarantees that 'error' is present here.
 return `Error occurred: ${state.error.message}`;
 }
}

4. 안전 제일: 완전성 검사

Discriminate Union 사용의 가장 큰 이점 중 하나는 Exhaustiveness Checking을 활용할 수 있다는 것입니다. 앞으로 새로운 상태 유형을 추가할 때 이를 처리하는 것을 잊었을 경우 컴파일러가 경고하기를 원할 것입니다.

우리는 never 유형을 사용하여 이를 달성할 수 있습니다:

function assertNever(value: never): never {
 throw new Error(`Unhandled state: ${JSON.stringify(value)}`);
}

function renderStateWithGuard<T>(state: FetchState<T>): string {
 switch (state.type) {
 case 'idle':
 return 'Waiting...';
 case 'loading':
 return 'Loading...';
 case 'success':
 return `Data: ${state.data}`;
 case 'error':
 return `Error: ${state.error.message}`;
 default:
 // If we add 'canceling' state in future & forget -> add a case for it,
 // TypeScript will raise a compile-time error here because 'state' cannot be reduced -> 'never'.
 return assertNever(state);
 }
}

결론

코드베이스에 Discriminate Union을 채택하면 다음과 같은 이점을 얻을 수 있습니다.

  1. 불가능한 상태 제로: 상태의 불가능한 변형은 구조적으로 금지됩니다.
  2. 예측 가능한 데이터 액세스: 방어적인 프로그래밍 패턴(예: null이 아닌 어설션 재정의)을 제거합니다.
  3. 컴파일 시 마음의 평화: 완전성 검사는 리팩토링 중에 내장된 안전망 역할을 합니다.

React 리듀서 작업, Redux 상태 또는 API 메시지 페이로드를 디자인하든 Discriminate Union은 채택해야 하는 핵심 TypeScript 패턴입니다.