aotoyae

[TS] Pick, Omit : 객체 프로퍼티 고르기, 생략하기 & Union 제거 본문

TypeScript

[TS] Pick, Omit : 객체 프로퍼티 고르기, 생략하기 & Union 제거

aotoyae 2024. 3. 5. 01:42

 

 

💡 합치는 거 말고 골라오거나, 생략해보자!

 

Pick

interface Product {
  id: string;
  name: string;
  price: number;
  membersOnly?: boolean;
}

type ProductInfo = Pick<Product, 'name' | 'price'>;

// ProductInfo 타입 값은 아래와 같다.
type ProductInfo = {
    name: string;
    price: number;
}

 

name, price 프로퍼티만 골라서 타입을 만들었다.

 

 

Omit

interface Product {
  id: string;
  name: string;
  price: number;
  membersOnly?: boolean;
}

type ProductInfo = Omit<Product, 'id' | 'membersOnly'>;

// ProductInfo 타입 값은 아래와 같다.
type ProductInfo = {
    name: string;
    price: number;
}

 

id, membersOnly 를 제외하고 타입을 만들었다.

 

 

💡 Union 을 제거해보자!

Coupon 의 타입은 네 개의 타입 중 하나일 수 있다.

PromotionCoupon 또는 EmployeeCoupon 또는 WelcomCoupon 또는 RewardCoupon

type Coupon = 
  | PromotionCoupon
  | EmployeeCoupon
  | WelcomCoupon
  | RewardCoupon
  ;

type InternalCoupon = EmployeeCoupon;
type PublicCoupon = Exclude<Coupon, InternalCoupon>;
// type PublicCoupon = PromotionCoupon | WelcomCoupon | RewardCoupon

 

EmployeeCoupon 에 해당하는 것만 제거하고 싶다면

Exclude 를 사용!