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

`Partial<T>` 와 `Required<T>`

~8 min · utility-types, partial, required, optionality

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"Partial 이 모든 거 optional 만들어. Required 가 반대. 둘 다 주마다 손 뻗을 한 줄 utility."

`Partial` — 모든 필드 optional

Partial<User> 가 User 타입 받고 모든 필드 optional 인 새 타입 만들어. { id: number; name: string }{ id?: number; name?: string } 됨. Update payload, configuration override, optional form state — caller 가 일부 필드만 제공할 어디든 유용.

Standard library 구현이 한 줄: type Partial<T> = { [K in keyof T]?: T[K] }. T 의 key 에 loop 돌고 각각에 `?` 적용하는 mapped 타입. Type Manipulation 트랙이 mapped 타입 자세히 다룸; 지금은 패턴 알아보면 충분.

`Required` — 모든 필드 필수

반대. Required<Profile> 가 optional 필드 가진 타입 받고 다 필수 만들어. 불완전 가능 object 받고 완전성 주장할 때, 또는 default-laden config 를 default 적용 후 strict 형태로 narrow 할 때 유용.

흔한 use case: update object

API endpoint 가 자주 부분 update payload 받음. function updateUser(id: number, patch: Partial<User>) 가 이걸 깨끗하게 타입하는 법: patch 가 User 필드의 어떤 subset 이든 담을 수. `Partial` 없으면 모든 필드 optional 인 전체 모양 손으로 써야 — 에러 가능성 있고 schema 변경에 깨지기 쉬워.

Partial 과 Required 는 거울상. 타입 있고 '그것의 가능 불완전 버전' 묘사하려면 Partial. 가능 불완전 타입 있고 '이제 완전해' 주장하려면 Required.

Code

Partial 과 Required 나란히·typescript
interface User {
  id: number;
  name: string;
  email: string;
}

// Partial — 모든 필드 optional.
type UserPatch = Partial<User>;
// { id?: number; name?: string; email?: string }

function updateUser(id: number, patch: UserPatch) {
  // patch 가 필드의 어떤 subset 이든 가질 수.
}

updateUser(1, { name: 'Pippa' });               // ✅
updateUser(1, { name: 'Pippa', email: '...' }); // ✅
updateUser(1, {});                              // ✅ — 빈 거 괜찮음

// Required — 반대.
interface Config {
  host?: string;
  port?: number;
  protocol?: 'http' | 'https';
}

type CompleteConfig = Required<Config>;
// { host: string; port: number; protocol: 'http' | 'https' }

function setup(cfg: CompleteConfig) {
  // cfg.host 등 존재 보장
}

External links

Exercise

interface Settings { theme: 'light' | 'dark'; fontSize: number; locale: string } 정의. 그다음 defaults: Settings 상수와 merge(defaults: Settings, overrides: Partial<Settings>): Settings 함수 써. Type system 이 overrides 에 유효하지 않은 필드 전달 시도 잡는지 확인.
Hint
merge{ ...defaults, ...overrides } 반환. Partial constraint 가 overrides 에 어떤 필드 subset 이든 가능 의미, 근데 key 가 Settings 에 없으면 compiler 가 불평.

Progress

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

댓글 0

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

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