본문 바로가기
  • [성공하는 개발자] - Developer
Node/TypeScript

7.Union

by Sein-JH 2021. 4. 17.
728x90

Union Types: OR

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

  type TileSize = 2 | 16 | 32;
  const tile: TileSize = 16;

| or union type 

타입으로 설정된 값이 left, right, up, down 으로 정의 되어 있다

move() 입력할시 4가지만 할당 할수 있게 된다

type TileSize 정의 함수는 정의된 숫자만 할당 가능하다 그렇치 않으면 오류 생김

 

Discriminated union

type SuccessState = {
    result: 'success';
    response: {
      body: string;
    };
  };
  type FailState = {
    result: 'fail';
    reason: string;
  };
  type LoginState = SuccessState | FailState;

  function login(): LoginState {
    return {
      result: 'success',
      response: {
        body: 'logged in!',
      },
    };
  }

  function printLoginState(state: LoginState) {
    if (state.result === 'success') {
      console.log(`ㅊㅋ ${state.response.body}`);
    } else {
      console.log(`ㅜㅜ ${state.reason}`);
    }
  }

공통 필드를 갖고 있는 타입들이 있을 때 키를 구별하는 기능(TS의 장점인 명확함을 잘 나타냄)
주의할 점 : type 으로 정해놓은 값은 똑같이 리턴해줘야함

직관적인 코드를 작성 할 수 있다

'Node > TypeScript' 카테고리의 다른 글

09. Inference 타입추론  (0) 2021.04.20
8.Intersection  (0) 2021.04.17
6.Aliases  (0) 2021.04.15
5.배열 Array or Tuple  (0) 2021.04.15
4.함수 타입(JS →TS)  (0) 2021.04.15

댓글