- TypeScript는 일반적인 타입 변환을 쉽게 하기 위해서 몇가지 유틸리티 타입을 제공합니다. 이러한 유틸리티는 전역으로 사용할 수 있습니다.
- 유틸리티 타입은 제네릭 타입이라고도 불리며, 타입 정의를 더욱 짧고 간단하게 사용할 수 있습니다.
Partial
Partial Type은 집합의 모든 프로퍼티를 선택적으로 타입을 생성할 수 있습니다. 이 유틸리티는 주어진 타입의 모든 하위 타입 집합을 나타내는 타입을 반환합니다.(부분집합)
예시
interface User {
email: string;
password: number;
}
type Person = Partial<Address>;
const me: MyInfo = {}; // 가능
const you: YouInfo = { email: "abcd@gmail.com" }; // 가능
const all: UserInfo = { email: "abcd@gmail.com", password: 1234 }; // 가능
interface Product {
id: number;
name: string;
price: number;
brand: string;
stock: number;
}
// Partial을 사용하면 인자에 type으로 Product의 모든 정보를 다 넣지 않아도 된다.
// 상품의 정보를 업데이트 (put) 함수 -> id, name 등등 어떤 것이든 인자로 들어올 수 있다.
interface UpdateProduct {
id?: number;
name?: string;
price?: number;
brand?: string;
stock?: number;
}
// Partial을 사용하지 않으면 위와 같이 정의할 수도 있다.
// 그러나 같은 인터페이스를 또 정의하는 것을 피하기 위해서 Partial을 사용한다.
function updateProductItem(prodictItem: Partial<Product>) {
// Partial<Product>이 타입은 UpdateProduct 타입과 동일하다
}
응용하기
// 아래 인터페이스를 다른 방법으로 아래와 같이 구현할 수 있다.
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]
};
Required
타입 집합의 모든 프로퍼티를 필수로 설정한 타입을 정의합니다.(Partial의 반대)
예시
interface UserProfile {
username?: string;
email?: string;
profilePhotoUrl?: string;
}
const user1: UserProfile = {
username: "Kim"
}
const user2: Required<UserProfile> = {
username: "Kim"
}
// Type '{ username: string; }' is missing the following properties from type 'Required<UserProfile>': email, profilePhotoUrl
Pick
Pick Type은 특정 타입에서 몇 개의 속성을 선택하여 타입을 정의합니다.
예시
interface Product{
id: number;
name: string;
price: number;
brand: string;
stock: number;
}
// 상품 목록 받아오기
function fetchProdcut():Promise<Product[]>{
// id, name, price, brand, stock 모두를 써야 한다.
}
type ShoppingItem = Pick<Product, "id" | "name" | "price">;
function displayProductDetail(shoppingItem: ShoppingItem){
// id, name, price의 일부만 사용 or 별도의 속성이 추가되는 경우가 있음
// 인터페이스의 모양이 달라질 수 있다
}
// 3. Partial
interface UpdateProduct {
id?: number;
name?: string;
price?: number;
brand?: string;
stock?: number;
}
function updateProductItem(prodictItem: Partial<Product>) {
// Partial<Product>이 타입은 UpdateProduct 타입과 동일하다
}
Omit
특정 속성만 제거한 타입을 정의합니다. (Pick의 반대)
예시
interface Product {
id: number;
name: string;
price: number;
brand: string;
stock: number;
}
type shoppingItem = Omit<Product, "stock">;
const apple: Omit<Product, "stock"> = {
id: 1,
name: "Kim",
price: 1000,
brand: "del"
};
참조
https://www.typescriptlang.org/ko/docs/handbook/utility-types.html
Documentation - Utility Types
Types which are globally included in TypeScript
www.typescriptlang.org
typescript - 유틸리티 타입 (Partial, Omit, Pick)
typescript - 유틸리티 타입 (Partial, Omit, Pick), 타입스크립트, ts
kyounghwan01.github.io
'TypeScript > TS' 카테고리의 다른 글
Mapped Types (0) | 2022.11.09 |
---|---|
읽기 전용 타입 - readonly, Readonly<T> (0) | 2022.11.02 |