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

2023. 12. 19. 18:07·기술/TypeScript

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'.
저작자표시 비영리 변경금지 (새창열림)

'기술 > TypeScript' 카테고리의 다른 글

[에러] typescript import 오류 : Could not find a declaration file for module 모듈에 대한 선언 파일을 찾을 수 없습니다.  (0) 2024.03.18
Interface vs Type 타입을 지정하는 또 다른 방법  (0) 2023.12.21
readonly 타입 설정, 불변성을 갖도록 만들기  (0) 2023.12.19
타입 축약과 타입의 확정 (Type Aliases 별칭, Narrowing, Assertion)  (1) 2023.12.18
Object(객체)에서 여러가지 타입을 지정해야 하는 경우 [key: type]  (0) 2023.12.18
'기술/TypeScript' 카테고리의 다른 글
  • [에러] typescript import 오류 : Could not find a declaration file for module 모듈에 대한 선언 파일을 찾을 수 없습니다.
  • Interface vs Type 타입을 지정하는 또 다른 방법
  • readonly 타입 설정, 불변성을 갖도록 만들기
  • 타입 축약과 타입의 확정 (Type Aliases 별칭, Narrowing, Assertion)
빔네모
빔네모
console.log("빔네모")
  • 빔네모
    bimnemo("개발")
    빔네모
  • 전체
    오늘
    어제
    • 기록 (156)
      • 기술 (44)
        • JavaScript (8)
        • TypeScript (9)
        • React.js (10)
        • Next.js (0)
        • 라이브러리,도구 (4)
        • HTML,CSS (4)
        • CS (5)
        • BE (4)
      • 개발 (99)
        • 프로젝트 (0)
        • 트러블슈팅 (5)
        • 알고리즘(코딩테스트) (94)
      • 정보 (4)
      • 취미 (9)
        • 감상 (9)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
빔네모
여러 타입을 만족하는 하나의 타입, 타입 합치기(Intersection Type, union/&)
상단으로

티스토리툴바