기술/TypeScript

여러 타입을 만족하는 하나의 타입, 타입 합치기(Intersection Type, union/&)

빔네모 2023. 12. 19. 18:07

1. Intersection Type

Intersection Type(교차 타입)은 TypeScript에서 두 개 이상의 타입을 합치는 방법 중 하나이다.

`& 연산자`를 사용하여 여러 타입을 하나로 합친다. 합쳐진 타입은 모든 타입의 특성을 가지게 된다.

interface Car {
  brand: string;
  speed: number;
}

interface Electric {
  battery: number;
}

type ElectricCar = Car & Electric;

const myCar: ElectricCar = {
  brand: 'Tesla',
  speed: 200,
  battery: 75,
};


//이렇게도 가능
type PositionX = { x: number };
type PositionY = { y: number };
type XandY = PositionX & PositionY
let 좌표 :XandY = { x : 1, y : 2 }

Intersection Type은 여러 타입을 결합할 때 유용하게 사용한다.

2. Union Type 

Union Type은 | 연산자를 사용하여 여러 타입 중 하나일 수 있는 타입을 나타낸다.

type StringOrNumber = string | number;

let value: StringOrNumber;
value = "Hello"; // 유효
value = 42;      // 유효
// value = true;  // 에러: 'boolean' 타입은 'string | number' 타입에 할당할 수 없음

 

타입별칭을 가져와서 합칠 수도 있다.

type Name = string;
type Age = number;
type NewOne = Name | Age;

 

3. object 타입을 정의한 type alias 두개를 & 기호로 합칠 때 , 중복된 속성이 있으면 어떻게 될까?

TypeScript에서는 중복된 속성 이름을 합치고 해당 속성의 값 타입을 never로 처리한다.

type A = { x: number };
type B = { x: string };
type C = A & B;

const c: C = { x: 42 };
//Type 'string' is not assignable to type 'never'.