Unions and Intersection Types

장유진·2022년 6월 28일
1

TypeScript

목록 보기
7/14

https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html

TypeScript에서는 단일 타입들을 결합하여 사용할 수 있다.

Union Types

수직선( | )을 사용하여 union type을 나타내면 여러 타입들 중 하나가 될 수 있음을 의미한다. 즉 string | number는 해당 변수가 string 또는 number가 될 수 있음을 의미한다.

function padLeft(value: string, padding: string | number) {
  // ...
}

Unions with Common Fields

union type을 사용할 때 모든 타입에서 공통적으로 가지고 있는 멤버들에만 접근할 수 있다.

interface Bird {
  fly(): void;
  layEggs(): void;
}

interface Fish {
  swim(): void;
  layEggs(): void;
}

declare function getSmallPet(): Fish | Bird;

let pet = getSmallPet();
pet.layEggs();

Bird와 Fish에서 layEggs라는 method만 공통으로 가지고 있으므로, Fish | Bird 타입인 변수에서는 layEggs만 사용이 가능하다.

Discriminating Unions

union type을 구성하는 모든 타입에 literal 값을 사용하는 공통 field를 추가하여 각각의 타입을 구분할 수 있도록 한다.

type NetworkLoadingState = {
  state: "loading";
};

type NetworkFailedState = {
  state: "failed";
  code: number;
};

type NetworkSuccessState = {
  state: "success";
  response: {
    title: string;
    duration: number;
    summary: string;
  };
};

// state를 사용하여 각 타입을 식별할 수 있다.
type NetworkState =
  | NetworkLoadingState
  | NetworkFailedState
  | NetworkSuccessState;

Union Exhaustiveness checking

union을 사용한다 하더라도 예외적인 케이스로 undefined 타입이 나올 수도 있음을 인지하고 이 경우에 에러를 해결하기 위해 조치를취해야 한다.

  1. string | undefined -> 이런 식으로 undefined 를 union type에 추가하여 예외 케이스를 처리한다.

  2. never 타입을 사용하여 컴파일러가 exhaustiveness를 확인할 수 있도록 한다.

Intersection Types

union type은 여러 개의 타입들 중 하나만 가능한 것이지만 intersection type은 여러 개의 타입을 하나로 합쳐 각각의 타입들의 속성을 전부 가지는 타입을 새로 만드는 것이다. intersection type은 & 기호를 사용하여 만들 수 있다.

interface A {
  a: number;
}

interface B {
  b: number;
}

// union은 A 또는 B 타입이 될 수 있다.
type union = A | B;

// intersection은 A와 B를 합친 타입으로, a: number와 b: number를 모두 가진다.
type intersection = A & B;
profile
프론트엔드 개발자

0개의 댓글