유틸리티 타입

Doum Kim·2021년 3월 22일
0

typescript

목록 보기
2/2

유틸리티 타입을 이용해 기존에 선언한 타입을 가지고 좀 더 편하게 새로운 타입을 정의할 수 있다.

Pick

원하는 속성을 선택해서 타입을 정의할 수 있다.

interface Product {
  name: string;
  id: number;
  price: number;
  brand: string;
}

const fetchProducts = (): Promise<Product[]> => {
  return new Promise((resolve) =>
    resolve([
      {
        name: "연필",
        id: 1,
        price: 10000,
        brand: "모닝글로리"
      }
    ])
  );
};

const getDetailItem = (product: Pick<Product, "name" | "price">): void => {
  console.log(product);
};

getDetailItem({
  name: "사과",
  price: 1000
});

Omit

지정된 속성을 제외한 타입을 정의할 수 있다.

const getDetailItem = (product: Omit<Product, "id" | "brand">): void => {
  console.log(product);
};

Partial

옵셔널한 타입을 정의할 수 있다.

type UpdateProduct = Partial<Product>;

유틸리티 타입을 직접 만들 수도 있는데 아래는 Partial를 직접 구현한 코드이다.

interface UserProfile {
  username: string;
  email: string;
  profilePhotoUrl: string;
}

interface UserProfileUpdate1 {
  username?: string;
  email?: string;
  profilePhotoUrl?: string;
}

type UserProfileUpdate2 = {
  username?: UserProfile["username"];
  email?: UserProfile["email"];
  profilePhotoUrl?: UserProfile["profilePhotoUrl"];
};

type UserProfileUpdate3 = {
  [p in "username" | "email" | "profilePhotoUrl"]?: UserProfile[p];
};

type UserProfileUpdate4<T> = {
  [p in keyof T]?: T[p];
};

const updateProfile: UserProfileUpdate4<UserProfile> = {
  username: "이름"
};

나머지 유틸리티 타입

위에서 살펴 본 3가지의 유틸리티 타입 이외에도 많은 유틸리티 타입이 있다.

https://www.typescriptlang.org/docs/handbook/utility-types.html

0개의 댓글