union과 intersection 타입

정민교·2023년 10월 6일
0

typescript

목록 보기
4/17

📒합집합(union) 타입

union 타입은 | 을 이용하여 정의할 수 있습니다.

// 합집합 타입 - Union 타입
let a: string | number;
// 합집합 타입 - Union 타입
let a: string | number | boolean;

a = 1;
a = "hello";
a = true;
// 합집합 타입 - Union 타입(배열 타입 정의)
let arr: (number | string | boolean)[] = [1, "hello", true];
// 합집합 타입 - Union 타입(객체 타입 정의)
type Dog = {
  name: string;
  color: string;
};

type Person = {
  name: string;
  language: string;
};

type Union1 = Dog | Person;

위와 같이 객체 union 타입을 정의하면 다음과 같은 객체들을 포함하는 타입이 됩니다.

(...)

let union1: Union1 = { // ✅
  name: "",
  color: "",
};

let union2: Union1 = { // ✅
  name: "",
  language: "",
};

let union3: Union1 = { // ✅
  name: "",
  color: "",
  language: "",
};

교집합(intersection) 타입

type Dog = {
  name: string;
  color: string;
};

type Person = {
  name: string;
  language: string;
};

type Intersection = Dog & Person;

let intersection1: Intersection = {
  name: "",
  color: "",
  language: "",
};

위와 같이 교집합 타입을 정의하면 Intersection 타입은 Dog 타입도 되고, Person 타입도 되는 객체들의 집합인 타입이 됩니다.

profile
백엔드 개발자

0개의 댓글