Notice
Recent Posts
Recent Comments
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Link
관리 메뉴

개발블로그

TypeScript - Union Types & 교차 타입 본문

TypeScript

TypeScript - Union Types & 교차 타입

춘식스 2022. 5. 27. 14:42
타입을 구성할 수 있는 방법 중 하나이다.
유니언 타입 or, |
교차 타입 and, &

유니언 타입(Union Types)

두 타입 중 하나만 사용해도 된다.
동일한 속성에 타입을 다르게해서 구분할 수 있는걸 식별 가능한 유니언 타입이라고 한다.
  • name이라는 동일한 타입을 줘서 두개의 인터페이스를 유니언 타입으로 사용이 가능하다.
// Union Types

interface Car {
  name: "car";
  color: string;
  start(): void;
}

interface Mobile {
  name: "mobile";
  color: string;
  call(): void;
}

function getGift(gift: Car | Mobile) {
  console.log(gift.color);
  if (gift.name === "car") {
    gift.start();
  } else {
    gift.call();
  }
}

교차 타입(Intersetion Types)

두개의 타입의 속성을 다 기입해줘야한다.
// Intersection Types

// 유니언 타입이 or이라면
// 교차타입은 and를 의미한다.

interface Car9 {
  name: string;
  start(): void;
}

interface Toy9 {
  name: string;
  color: string;
  price: number;
}

const toyCar: Toy9 & Car9 = {
  name: "타요",
  start(){},
  color: "blue",
  price: 1000
}
// Toy와 Car에 모든 속성을 다 기입해줘야한다.
// & == and

'TypeScript' 카테고리의 다른 글

TypeScript - 유틸리티 타입  (0) 2022.05.27
TypeScript - Literal Types  (0) 2022.05.27
TypeScript - Class  (0) 2022.05.27
TypeScript - Generics  (0) 2022.05.27
TypeScript - Type Alias  (0) 2022.05.27
Comments