[한입] 맵드타입 기반 유틸리티 타입들

TK·2023년 12월 22일
0

[강의] 한입 시리즈

목록 보기
58/59

맵드타입 기반 유틸리티 타입들


✏️Partial<T>

  • 특정 객체 타입의 모든 프로퍼티를 선택적 프로퍼티로 바꿔주는 타입
interface Post {
  title: string;
  tags: string[];
  content: string;
  thumbnailURL?: string;
}

// 직접 구현
type Partial<T> = {
  [key in keyof T]?: T[key]; // 키(맵드타입) : 밸류(인덱스드엑세스타입)
};

const draft: Partial<Post> = {
  title: "제목 나중에",
  content: "초안...",
};

✏️Required<T>

  • 특정 객체 타입의 모든 프로퍼티를 필수 프로퍼티로 바꿔주는 타입
interface Post {
  title: string;
  tags: string[];
  content: string;
  thumbnailURL?: string;
}

// 직접 구현
type Required<T> = {
  [key in keyof T]-?: T[key]; // 물음표(선택적)을 제거한다.
};

const withThumbnailPost: Required<Post> = {
  title: "한입 타스 후기",
  tags: ["ts"],
  content: "",
  thumbnailURL: "https://...",
};

✏️Readonly<T>

  • 특정 객체 타입의 모든 프로퍼티를 읽기 전용 프로퍼티로 바꿔주는 타입
interface Post {
  title: string;
  tags: string[];
  content: string;
  thumbnailURL?: string;
}

// 직접 구현
type Readonly<T> = {
  readonly [key in keyof T]: T[key];
};

const readonlyPost: Readonly<Post> = {
  title: "보호된 게시글 입니다.",
  tags: [],
  content: "",
};

readonlyPost.content = ""; // ❌오류
profile
쉬운게 좋은 FE개발자😺

0개의 댓글