August 21, 2021
본 내용은 인프런에서 캡틴판교님의 타입스크립트 강의를 듣고 정리한 것입니다.
특정 타입의 일부분을 부분적으로 만족할 때 사용한다(optional처럼 사용한다).
interface Address {
email: string;
address: string;
}
type MayHaveEamil: Partial<Address>;
const me: MayHaveEmail = {}; // 아예 속성이 없을때도 만족
const you: MayHaveEmail = { email: 'sarah@test.com' }; // 일부분인 email만 쓸때도 가능
const all: MayhaveEmail = { email: 'all@test.com', address: 'Seoul' }// 전부일때도 가능
interface Product {
id: number
name: string
price: number
brand: string
stock: number
}
// 특정 상품 정보를 업데이트하는 함수
function updateProductItem(productItem: Product) {
// Product를 그대로 쓰면 name만 바꿔야하는 경우에도 id~stock부터 전부 갱신됨.
}
// UpdateProduct를 새로 만들고 ?를 달아주면 원하는 효과를 낼 수 있지만 불필요하게 인터페이스를 생성함.
interface UpdateProduct {
id?: number
name?: string
price?: num ber
brand?: string
stock?: number
}
// Partial<Product>로 처리해주면 UpdateProduct와 동일한 효과를 낸다.
function updatePRoductItem2(productItem: Partial<Product>) {}