utility type

일반적인 타입 변환을 쉽게 하기 위해 제공되는 빌트인 타입 타입코드의 재사용성과 간결성을 높이는 데 도움이 되며, 기존 타입들을 기반으로 새로운 타입을 생성할 수 있게 함

Partial<Type>

: Partial 유틸리티 타입은 주어진 타입의 모든 프로퍼티를 선택적으로 만듦 즉, 모든 프로퍼티optional로 변환됨

interface User {
  name: string;
  age: number;
  email: string;
}

const updateUser: Partial<User> = {
  name: "John" // email과 age는 선택적으로 포함되지 않을 수 있음
};

//

interface Todo {
  title: string;
  description: string;
}
 
function updateTodo(todo: Todo, **fieldsToUpdate: Partial<Todo>**) {
  return { ...todo, ...fieldsToUpdate };
}
 
const todo1 = {
  title: "organize desk",
  description: "clear clutter",
};
 
const todo2 = updateTodo(todo1, {
  description: "throw out trash",
});

console.log(todo2)

/* output

{
  "title": "organize desk",
  "description": "throw out trash"
} 

*/

Required<Type>

:Required 유틸리티 타입은 주어진 타입의 모든 프로퍼티를 필수로 만듦 즉, 선택적 프로퍼티가 모두 필수로 변환됨 (Partial과 반대)

interface User {
  name?: string;
  age?: number;
  email?: string;
}

const user: Required<User> = {
  name: "John",
  age: 25,
  email: "[email protected]"
}; // 모든 프로퍼티가 필수로 변환

interface Props {
  a?: number;
  b?: string;
}
 
const obj: Props = { a: 5 };
 
const obj2: Required<Props> = { a: 5 };

//Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.

Readonly<Type>

:Readonly 유틸리티 타입은 주어진 타입의 모든 프로퍼티를 읽기 전용으로 만듦. 즉, 생성된 객체의 프로퍼티를 변경할 수 없음

interface Todo {
  title: string;
}
 
const todo: Readonly<Todo> = {
  title: "Delete inactive users",
};
 
todo.title = "Hello";// 오류 읽기 전용 프로퍼티로서 title에 할당할 수 없음

Record<Keys,Type>

: Record 유틸리티 타입은 특정 키(Key) 집합에 대해 동일한 타입을 가지는 객체 타입을 만듦