174일차(2) - Union & Intersection Type

김민찬·2021년 10월 30일
0

취업으로의 여정

목록 보기
179/196
post-thumbnail

Union Type

Union Type은 or 연산자를 생각하면 된다.
하나 이상의 타입을 사용할 수 있게 해주는 것이다.

만약 정해지지 않은 unKnown이라는 변수를 string 나 number 값 중에 하나를 사용할 것이면 아래와 같이 선언 하면 된다.

let unKnown: string | number;

// unKnown은 string이나 number 값 중 하나여서 에러가 발생하지 않는다.
unKnown = 'hello';
unKnown = 10;

// unKnown에 boolean값은 할당 할 수 없다.
unKnown = true; // TypeError

특징으로 예시와 같이 두 개의 인터페이스를 생성한후, 하나의 변수에 선언하면, 공통속성에만 접근이 가능하다.

interface Movie {
  title: string;
  director: string;
}

interface Drama {
  title: string;
  episodes: number;
}

function watchNetflix(choice: Movie | Drama) {
  choice.title;
  choice.director; // error
  choice.episodes; // error
}

물론 any를 사용할 수도 있지만, 그렇게 사용하면 TypeScript를 사용하는 의미가 퇴색된다.

Intersection Type

Intersection Type은 and 연산자를 생각하면 된다.

let unKnown = string & number & boolean;

그런데 배우면서 느낀점이 Union Type보다 매우 활용도가 떨어질 것 같다.
string이나 number인 변수를 찾을 수는 있는데, string이면서 동시에 number인 변수를 찾을 일이 있을까?

Union Type과 다르게 Intersection Type은 모든 속성이 다 포함되어 있어야 한다.

interface Movie {
  title: string;
  director: string;
}

interface Drama {
  title: string;
  episodes: number;
}

function watchNetflix(choice: Movie & Drama) {
  choice.title;
  choice.director;
  choice.episodes;
}

참고자료

캡틴판교 - 타입스크립트

profile
두려움 없이

0개의 댓글