Record<Keys, Type>
TypeScript에서 Record는 유틸리티 타입 중 하나로, 객체 타입을 간편하게 정의할 수 있게 해주는 도구이다.
특히 "특정 key 집합과 그에 대응하는 값 타입"을 정의할 때 유용해요.
Record<Keys, Type>
- Keys : 객체의 key로 사용할 수 있는 타입(보통 문자열 리터럴 union)
- Type : 해당 key가 가지는 value의 타입
이걸 통해 정해진 키만을 가지며, 그 값은 모두 동일한 타입인 객체를 만들 수 있다.
🔍 왜 쓰는가?
- 객체의 key/value 구조를 타입으로 선언할 때 반복 없이 간결하게 표현할 수 있음
- 특정 key에만 제한을 두고, 그 값들은 같은 타입으로 통일할 수 있음
🎯 언제 쓰면 좋을까?
- 정해진 key 목록이 있고, 모두 같은 타입의 값을 가지게 하고 싶을 때
- 객체의 타입을 반복하지 않고 간결하게 선언하고 싶을 때
✅ 예제
📌 예제 1: 제한된 키 집합
type Fruit = "apple" | "banana" | "orange";
const fruitColors: Record<Fruit, string> = {
apple: "red",
banana: "yellow",
orange: "orange",
};
아래의 표현이랑 같은 뜻이라고 보면 된다.
type FruitColors = {
apple: string;
banana: string;
orange: string;
};
📌 예제 1: 중첩된 Record
type Role = "admin" | "user";
type Permission = "read" | "write" | "delete";
const access: Record<Role, Record<Permission, boolean>> = {
admin: {
read: true,
write: true,
delete: true,
},
user: {
read: true,
write: false,
delete: false,
},
};