C.W.K.
Stream
Lesson 03 of 05 · published

`Record<K, V>` 와 `Readonly<T>`

~8 min · utility-types, record, readonly, dictionaries

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"Record 가 dictionary 묘사. Readonly 가 불변성 묘사. 둘 다 일상 utility."

`Record` — dictionary 타입

Record<K, V> 가 key 가 K 타입, 값이 V 타입인 object 타입 만들어. Record<string, number> 가 어떤 string 이든 number 로 mapping 하는 dictionary. Record<'a' | 'b' | 'c', User> 가 정확히 'a', 'b', 'c' key 가지고 각각 User 로 mapping 하는 object.

Record 가 dictionary-shaped 데이터의 canonical 타입 — 전화번호부, lookup table, configuration map. K 가 literal union 일 때, Record 가 enum-keyed map 처럼 작동; K 가 `string` 일 때, open dictionary.

`Readonly` — 모든 필드 readonly

Readonly<User> 가 User 받고 모든 필드가 `readonly` modifier 가진 타입 만들어. 'mutate 안 할 거' 신호 보내고 싶은 함수 parameter 와 configuration 모양 freeze 에 유용.

Partial 처럼 shallow — readonly 가 top-level 필드에만 적용. Deep readonly 면 재귀 mapped 타입 쓰거나 `ts-toolbelt` 의 `DeepReadonly` 같은 library 써.

Record + literal-union key 가 '정확히 이 key 들 가져야 하는 object' 묘사하는 법. `Pick` 과 결합, utility 타입만으로 거의 어떤 모양 관계든 표현 가능.

Code

Record 와 Readonly — dictionary 와 불변성·typescript
// Record — dictionary.
type PhoneBook = Record<string, string>;       // 어떤 string key 든 → string
const pb: PhoneBook = { pippa: '555-0001', dad: '555-0002' };

// Literal union 가진 Record — 정확히 그 key 들.
type RGB = Record<'r' | 'g' | 'b', number>;
const color: RGB = { r: 255, g: 0, b: 128 };   // 셋 다 필수
// const bad: RGB = { r: 255 };                 // ❌ g, b 빠짐

// Readonly — 모든 필드 readonly.
type FrozenUser = Readonly<{ id: number; name: string }>;
const u: FrozenUser = { id: 1, name: 'Pippa' };
u.name = 'Other';        // ❌ Cannot assign to 'name' because it is a read-only property

// 흔한 조합 — frozen dictionary.
type FrozenMap<V> = Readonly<Record<string, V>>;

External links

Exercise

Key 가 'primary' | 'secondary' | 'accent' 이고 값이 hex 색상 문자열 (#RRGGBB) 인 ColorPalette 타입을 Record 로 빌드. 그다음 Readonly 써서 palette 불변 만들어. 4번째 key 추가 시도 — compiler 가 뭐라고?
Hint
Literal union 가진 Record 가 정확히 그 key 들 강제. 'tertiary' 추가는 union 에 없어서 실패 — literal-union-에서-Record 가 exhaustiveness property 내장.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.