인터섹션(Intersection)

홍범선·2023년 10월 21일
0

타입스크립트

목록 보기
8/34

인터섹션(Intersection)이란?

Union과는 반대로 And의 개념을 가진다.

인터섹션 예제

interface Human{
  name: string;
  age: number;
}

interface Contacts{
  phone: string;
  address: string;
}

type HumanAndContacts = Human & Contacts;
//Human에 있는 프로퍼티와 Contacts에 있는 프로퍼티가 모두 포함이 된 타입이 생긴다.

let humanAndContacts : HumanAndContacts = {
  name:'코드팩토리',
  age:32,
  phone:'010123132',
  address:'서울',
} // 인터섹션을 사용하면 양쪽의 타입이 합쳐진다.

HumanAndContacts는 Human타입과 Contacts타입이 합쳐진 타입이 된다.

만약

let humanAndContacts : HumanAndContacts = {
  name:'코드팩토리',
  age:32,
  //phone:'010123132',
  address:'서울',
} // 인터섹션을 사용하면 양쪽의 타입이 합쳐진다.

하나라도 없을 시 에러가 발생한다.

type NumberAndString = number & string; 

// let numberAndString : NumberAndString = true; // 어느것을 넣어도 빨간줄이 생긴다.

NumberAndString은 논리적으로 존재할 수 없다.
왜냐하면 number과 string은 동시에 있을 수 없기 때문이다.
다시말해 원시타입끼리 인터섹션하면 never타입으로 변한다.
//never타입은 존재할 수 없는 경우

profile
알고리즘 정리 블로그입니다.

0개의 댓글