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

Union 타입: `A | B`

~9 min · unions-intersections, union, type-modeling

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"대부분 실제 값이 여럿 중 하나야. Union 이 그걸 type system 한테 말하는 법."

Union 이 묘사하는 것

Union 타입 A | B 가 타입이 나열된 대안 중 하나인 값 묘사. 값이 주어진 순간에 정확히 그 타입 중 하나 — 절대 둘 다 아니고, 절대 안 함도 아냐. Compiler 가 control flow 통해 어느 것인지 추적.

Union 이 TypeScript 에서 실세계 데이터 모델링하는 가장 흔한 방법. 4개 문자열 중 하나일 수 있는 status 필드. 성공 또는 에러일 수 있는 응답. 문자열 OR 문자열 반환 함수 받는 configuration 옵션. 다 union.

Union 값의 연산

Union 의 모든 멤버에 존재하는 property 나 method 만 접근/호출 가능. (string | number).toUpperCase() 실패 — number 에 toUpperCase 없으니까. 타입-specific 연산 쓰려면 먼저 narrow — typeof 체크, instanceof, in operator, 또는 커스텀 type guard. Narrowing 트랙에서 깊이 다뤄.

흔한 패턴

  • Literal-string union: 'idle' | 'loading' | 'done' — enum-by-convention 패턴.
  • Nullable: string | null 또는 string | undefined — 명시적 optional.
  • Tagged 모양 union: { kind: 'a'; x: number } | { kind: 'b'; y: string } — discriminated union (다다음 lesson).
  • Function-or-value: string | (() => string) — literal 이나 producer 받음.
일반 규칙: 값이 진짜로 여러 타입 중 하나일 수 있으면 — '가끔 A, 가끔 B 인데 호환되는' 게 아니라 실제로 '이거 OR 저거' — union 으로 모델링. Compiler 가 두 가능성 다 추적하고 각각 처리하라고 강제.

피파의 고백

Union 이 cwkPippa 가 거의 모든 state 모델링하는 법. BrainName 이 union. Conversation status 가 union. 성공 또는 실패할 수 있는 모든 API 응답이 union. TypeScript 에서 얻는 type-system 가치 대부분이 union + narrowing — 거의 다른 어떤 기능보다 더.

Code

Union — '이 중 하나' 모델링·typescript
// Union 어디서나.
type Id = string | number;
const a: Id = 'abc';
const b: Id = 42;

// 두 멤버에 공통인 것만 쓸 수 있어.
function print(id: Id) {
  // id.toUpperCase();  // ❌ number 가 toUpperCase 없음
  console.log(String(id));   // ✅ 둘 다 작동
  if (typeof id === 'string') {
    id.toUpperCase();        // ✅ narrow 됨
  }
}

// 흔한 패턴.
type Status = 'idle' | 'loading' | 'done' | 'error';
type Nullable<T> = T | null;
type Response = { ok: true; data: User } | { ok: false; error: string };

External links

Exercise

number | string | Date 받고 포맷된 문자열 반환하는 format 함수 써. 함수 안에서 narrow 해야 함. 어떤 narrowing operator 먼저 손 뻗어 — typeof, instanceof, 또는 in?
Hint
typeof 가 primitive (number, string) 에 작동. instanceof 가 class instance (Date) 에 작동. 둘 다 이 연습에 적용; sequence 로 써.

Progress

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

댓글 0

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

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