https://www.typescriptlang.org/ko/docs/handbook/utility-types.html#excludetype-excludedunion
Documentation - Utility Types
Types which are globally included in TypeScript
www.typescriptlang.org
Partial<Type>
// Partial<Type>
type Post = {
title: 'string'
index: number
content: string
}
const updatePostContent = (post:Post, updateContent: Partial<Post>):Post => {
return {...post, ...updateContent}
}
- Partial<Type>은 Type의 하위집합을 의미한다.
- 위 예제 처럼 Post 타입을 가진 객체에 Partial<Post> 타입을 구조분해할당 해도 하위집합을 새로 덧씌우는 개념이므로 유효한 타입이다.
Required<Type>
// Required<Type>
type Farm = {
pig?: number
cow?: number
dog?: number
hen?: number
}
const farmA:Farm = {
pig: 5,
cow: 1
}
const farmB: Required<Farm> = {
pig: 100,
cow: 100,
dog: 100,
hen: 100
}
- Required<Type>은 타입의 모든 요소를 반드시 필수적으로 기입하게 만드는 유틸리티 타입이다.
- 기준이 되는 Farm 타입은 모든 프로퍼티가 옵셔널하다.
- Farm을 Required로 감싸면 타입 내 선언된 모든 프로퍼티를 필수적으로 입력해야 한다.
Record<Keys, Type>
// Record<Keys,Type>
type animalKey = "lion" | "tiger" | "horse" | "monkey"
type animalInfo = {
age: number,
country: string
feed: "meat" | "hay" | "fruit"
size: "small" | "middle" | "big"
}
const zooFamily: Record<animalKey, animalInfo> = {
lion: {
age: 5,
country: "africa",
feed: "meat",
size: "middle"
},
tiger: {
age: 5,
country: "africa",
feed: "meat",
size: "middle"
},
horse: {
age: 5,
country: "africa",
feed: "hay",
size: "big"
},
monkey: {
age: 5,
country: "africa",
feed: "fruit",
size: "small"
}
}
- Keys에 타입을 대입시키는 유틸리티 타입이다.
- 키의 집합으로 타입을 생성하고 생성된 타입의 프로퍼티를 다른 타입과 매핑하는데 사용한다.
'Typescript' 카테고리의 다른 글
객체 키 타입의 유니온 추출 및 활용 (1) | 2024.01.09 |
---|---|
유틸리티 타입 (Parameters) (0) | 2023.11.21 |
keyof typeof typesomething (0) | 2023.09.05 |
React 컴포넌트에 타입스크립트 적용 (0) | 2023.09.05 |
catch문의 error 타입이 any 또는 unknown여야 하는 이유 (0) | 2023.08.09 |