TypeScript/TypsScript - 실전 프로젝트

1. 유틸리티 타입 | 유틸리티 타입 사례 - Partial , Pick

DEV-Front 2023. 10. 15. 02:49
반응형

유틸리티 타입이란?

  • 이미 정의해 놓은 타입을 변환할때 사용하기 좋은 타입 문법
  • 인터페이스, 제네릭보다 더 간결한 문법으로 타입을 정의할 수 있음 

Partial

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" }; // 가능
  • 파셜 타입은 특정 타입의 부분 집합을 만족하는 타입을 정의할 수 있음.

https://kyounghwan01.github.io/blog/TS/fundamentals/utility-types/#partial

 

typescript - 유틸리티 타입 (Partial, Omit, Pick)

typescript - 유틸리티 타입 (Partial, Omit, Pick), 타입스크립트, ts

kyounghwan01.github.io


Pick

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

}


// 상품 목록 받아오기 위한 API 함수
function fetchProduct() : Promise<Product[]>{
    // ..
}

// 하나의 상품 정보를 화면에 보여줌
function displayProductDetail(shoppingItem : Pick<Product, 'id' | 'name' | 'price'> ){
    //..
}
  • Product 인터페이스의 구성요소중 일부만 사용하고 싶을때
    Pick이라고하는 유틸리티 타입을 이용해서 사용할 수 있다.

 

반응형