[TS] Partial - Utility Type

Jang Seok Woo·2022년 7월 8일
0

실무

목록 보기
94/136

Partial은 말 그대로 객체의 부분집합으로 객체를 구성할 수 있게 해주는 것입니다.

유틸리티 타입, 제네릭 타입 이라도 불립니다.

파셜 타입은 특정 타입의 부분 집합을 만족하는 타입을 정의할 수 있습니다.

  1. 부분집합 예시
interface Address {
  email: string;
  address: string;
}

type MyEmail = Partial<Address>;
const me: MyEmail = {}; // 가능
const you: MyEmail = { email: "noh5524@gmail.com" }; // 가능
const all: MyEmail = { email: "noh5524@gmail.com", address: "secho" }; // 가능
  1. 부분집합을 인터페이스를 사용한 예시
interface Address {
  email: string;
  address: string;
}

type MyEmail = Partial<Address>;
const me: MyEmail = {}; // 가능
const you: MyEmail = { email: "noh5524@gmail.com" }; // 가능
const all: MyEmail = { email: "noh5524@gmail.com", address: "secho" }; // 가능

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

// Partial - 상품의 정보를 업데이트 (put) 함수 -> id, name 등등 어떤 것이든 인자로 들어올수있다
// 인자에 type으로 Product를 넣으면 모든 정보를 다 넣어야함
// 그게 싫으면
interface UpdateProduct {
  id?: number;
  name?: string;
  price?: number;
  brand?: string;
  stock?: number;
}
// 위와 같이 정의한다.
// 그러나 같은 인터페이스를 또 정의하는 멍청한 짓을 피하기 위해서 우리는 Partial을 쓴다.
function updateProductItem(prodictItem: Partial<Product>) {
  // Partial<Product>이 타입은 UpdateProduct 타입과 동일하다
}
  1. Partial 구현 예시
// 아래 인터페이스를 다른 방법으로 아래와 같이 구현 가능하다
interface UserProfile {
  username: string;
  email: string;
  profilePhotoUrl: string;
}

type partials = Partial<UserProfile>

// #1
type UserProfileUpdate = {
  username?: UserProfile["username"];
  email: UserProfile["email"];
  profilePhotoUrl?: UserProfile["profilePhotoUrl"];
};

// #2 - 맵드 타입
type UserProfileUpdate = {
  // index signatures
  [p in 'username' | 'email' | 'profilePhotoUrl']? = UserProfile[p]
};

type UserProfileKeys = keyof UserProfile // 'username' | 'email' | 'profilePhotoUrl'
// #3
type UserProfileUpdate = {
  [p in key of UserProfile]? = UserProfile[p]
};

// #4 - 파셜
type RealPartial<T> = {
  [p in key of T]? = T[p]
};
profile
https://github.com/jsw4215

0개의 댓글