앞서 배웠던 것들을 사용하여 재 사용 가능한 utility type 을 만들 수 있습니다. 직접 만들어 사용하는 것 도 좋지만, 자주 사용하는 것 들에 대해 typescript 는 내장 utility type 들을 제공해 줍니다.
이 섹션에서는 자주 사용하는 utility type 을 소개합니다.
Awaited<Type>
Released:
Promise 로 감싸져 있는 타입을 추출합니다.
Example
type A = Awaited<Promise<string>>;
// type A = string
type B = Awaited<Promise<Promise<number>>>;
//type B = number
type C = Awaited<boolean | Promise<number>>;
//type C = number | boolean
Partial<Type>
Released:
객체의 모든 속성이 optional 한 타입을 구성합니다.
Example
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",});
Required<Type>
Example
interface Props {
a?: number;
b?: string;
}
const obj: Props = { a: 5 };
const obj2: Required<Props> = { a: 5 }; //Error : Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.