본문 바로가기

TypeScript

[TypeScript] 유니온 타입은 언제 사용하는가?

유니온 타입은 합집합의 개념이다.

 

유니온 타입(Union Type)이란?

OR 연산자와 같이 'A이거나 B이다' 라는 의미의 타입이다.

 

1. 여러가지 타입을 연결할 때

const printAge(age: string | number): void => {
  if (typeof age === 'number') {
    age.toFixed();
    console.log(age);
  }
  if (typeof age === 'string') {
    console.log(age);
  }
}

 

2. 타입 별칭 (Type Alias)를 통해 enum처럼 활용하기

타입 별칭이란 한마디로 '사용자 지정 타입'이다.

사용자가 커스텀으로 생성한 새로운 타입을 의미한다.

type Direction = 'left' | 'right' | 'up' | 'down';
const move = (direction: Direction): void => {
  console.log(direction);
}
move('down');

 

3. 유니온 구별하기 (Discriminated Union)

공통 필드를 갖고 있는 타입들이 있을 때, 공통 필드를 통해 유니온을 구별할 수 있다.

아래는 state라는 공통 필드를 가진 타입들을 다루는 예시이다.

type LoginFailState = {
  state: "fail";
  code: number;
};

type LoginSuccessState = {
  state: "success";
  response: {
    title: string;
    summary: string;
  };
};

// 위 타입들을 대표하는 타입을 만들었지만, 무엇에 해당하는지 아직 확실하지 않다.
type LoginState = LoginFailState | LoginSuccessState;

const loginStatus = (state: LoginState): string => {
  state.code;		// error, 모든 타입에 공유되지 않는 프로퍼티에는 접근 불가

  switch (state.state) {
    case "fail":
      // 여기서 타입은 LoginFailState일 것이며, 따라서 'code' 필드에 접근할 수 있다.
      return `Error ${state.code} downloading`;
    case "success":
      // 여기서 타입은 LoginSuccessState일 것이며, 따라서 'response' 필드에 접근할 수 있다.
      return `Downloaded ${state.response.title} - ${state.response.summary}`;
  }
}