인덱스 접근 타입과 맵드 타입
인덱스 접근 타입 (Indexed Access Types)은 Type["property"] 형태로 객체 내부의 특정 속성 타입만 쏙 빼내는 기능입니다.
맵드 타입 (Mapped Types)은 [K in keyof T] 문법을 사용해 기존 객체 타입의 모든 속성을 순회하면서 새로운 타입을 찍어내는 마법 같은 팩토리 기능입니다.
<!-- ==========================================
// 📂 ts-advanced/mapped-types.ts
// ========================================== -->
<script>
interface APIResponse {
userId: number;
userName: string;
isActive: boolean;
}
// 1. 인덱스 접근 타입 (특정 속성 타입 빼오기)
type IdType = APIResponse["userId"]; // number
// 2. 맵드 타입 팩토리 (모든 속성을 boolean으로 변환)
// [K in keyof T] 는 T의 모든 키를 순회하겠다는 뜻입니다.
type BooleanMap<T> = {
[K in keyof T]: boolean;
};
type FlagResponse = BooleanMap<APIResponse>;
/* 생성된 타입:
type FlagResponse = {
userId: boolean;
userName: boolean;
isActive: boolean;
}
*/
// 3. 실무 예제: 모든 속성을 읽기 전용(readonly)으로 만들기
type MyReadonly<T> = {
readonly [K in keyof T]: T[K]; // T[K]가 인덱스 접근 타입!
};
const user: MyReadonly<APIResponse> = {
userId: 1,
userName: "Bob",
isActive: true
};
// user.userName = "Alice"; // ❌ Error: Cannot assign to 'userName' because it is a read-only property.
</script>