특정 타입을 반복적으로 사용하면 불필요한 코드들이 계속 생겨날 수 있기 에 따로 타입 별칭을 이용해서 코드의 가독성을 높일 수 있다.

// 튜플
type NumberPoint = [number, number];

타입 별칭을 이용해서 NumberPoint 라는 타입을 만들어서 튜플타입의 반복되는 코드를 줄일 수 있다.

InterSection


interface의 extends 와 역할이 비슷하다.

interface Id {
  id: string;
}

interface Timestamp {
  createdAt: Date;
  updatedAt: Date;
}

type Product = Id & {
  name: string;
  price: number;
  membersOnly?: boolean;
};

type User = Id &
  Timestamp & {
    username: string;
    email: string;
  };

type Review = Id &
  Timestamp & {
    productId: string;
    userId: string;
    content: string;
  };

인터페이스의 중복되는 타입을 지정해준 뒤 type 지정으로 상속받게 사용이 가능하다.

interface vs 타입별칭


interface 의 상속과 intersection 의 가장 큰 차이점은 intersection 은 두 가지 이상의 타입을 한 번에 합칠 수 있다. 되도록 interface 를 권장하지만 타입별칭도 사용 될 수 있다.

타입별칭은 언제 쓸까?


타입 별칭은 타입에 이름 을 정하는 문법이기에 복잡한 타입을 만들고, 그 타입을 여러 곳에서 활용할 때, 사용하면 된다. 아래의 예와 같이 복잡한 타입을 만들고 재사용 하면 된다.

type Point = [number, number];
type SearchQuery = string | string[];
type Result = SuccessResult | FailedResult;
type Coupon = 
  | PromotionCoupon
  | EmployeeCoupon
  | WelcomCoupon
  | RewardCoupon
  ;