TypeScript: Utility Types

Outclass·2022년 7월 25일
0
type MockRepository<T = any> = Partial<Record<keyof Repository<T>, jest.Mock>>;

위와 같은 코드를 보고 정신이 혼미해져서 타입 관련 정리를 해본다.

Partial< Type >

  • <>안의 타입을 모두 optional하게 만들어준다.
interface Todo {
  title: string;
  description: string;
}
 
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  return { ...todo, ...fieldsToUpdate };
}
 
const todo1 = {
  title: "organize desk",
  description: "clear clutter",
};

//todo1의 경우 title과 description이 모두 있어야 하지만
//Partial<Todo>의 경우 타입이 optional하기 때문에 title이 없어도 된다
const todo2 = updateTodo(todo1, {
  description: "throw out trash",
});

Record<Keys,Type>

  • key의 집합인 Keys에 Type을 매핑한다
interface PageInfo {
  title: string;
}
 
type Page = "home" | "about" | "contact";
 
//home, about contact에 각각 pageinfo타입이 매핑된다.
const nav: Record<Page, PageInfo> = {
  about: { title: "about" },
  contact: { title: "contact" },
  home: { title: "home" },
};
 

정리

type MockRepository<T = any> = Partial<Record<keyof Repository<T>, jest.Mock>>;
  • 위 코드를 해석해보자면...
  • Repository의 key들의 집합에 jest.mock의 타입을 매핑하고
  • 그 타입들을 모두 Partial로 optional하게 만든다!(여전히 어렵다)

참고링크

profile
When you stop having big dreams that’s when you’ve died, despite not being buried yet.

0개의 댓글