타입스크립트의 Partial<T>, Required<T>, Readonly<T>는 맵드 타입 기반의 유틸리티 타입으로, 객체 타입의 프로퍼티를 선택적, 필수, 읽기 전용으로 변환함. 이들은 제네릭 + keyof + 맵드 타입의 조합으로 구현할 수 있음.
객체 타입의 모든 프로퍼티를 선택적(optional)으로 변환함.
interface Post {
title: string;
tags: string[];
content: string;
thumbnailURL?: string;
}
const draft: Partial<Post> = {
title: "제목 나중에 짓자",
content: "초안...",
};
type Partial<T> = {
[key in keyof T]?: T[key];
};
객체 타입의 모든 프로퍼티를 필수(required)로 변환함.
interface Post {
title: string;
tags: string[];
content: string;
thumbnailURL?: string;
}
const withThumbnailPost: Required<Post> = {
title: "한입 타스 후기",
tags: ["ts"],
content: "",
thumbnailURL: "https://...",
};
type Required<T> = {
[key in keyof T]-?: T[key];
};
객체 타입의 모든 프로퍼티를 읽기 전용(readonly)으로 변환함.
interface Post {
title: string;
tags: string[];
content: string;
thumbnailURL?: string;
}
const readonlyPost: Readonly<Post> = {
title: "보호된 게시글입니다.",
tags: [],
content: "",
};
readonlyPost.content = "해킹당함"; // 오류 발생
type Readonly<T> = {
readonly [key in keyof T]: T[key];
};
Partial<T>: 모든 프로퍼티를 선택적으로 만듦 (?).Required<T>: 모든 선택적 프로퍼티를 필수로 만듦 (-?).Readonly<T>: 모든 프로퍼티를 읽기 전용으로 만듦 (readonly).맵드 타입 + keyof + 제네릭 조합으로 구현 가능함.