C.W.K.
Stream
Lesson 06 of 07 · published

Conditional 타입: `T extends X ? A : B`

~12 min · generics, conditional-types, type-computation

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"타입-레벨 ternary. Compiler 가 값 계산하듯 타입 계산."

모양

Conditional 타입이 T extends X ? A : B 형태. 타입 레벨에서 평가: T 가 X 에 assignable 하면 타입 A; 아니면 B. 여기 `extends` 가 generic constraint 에 쓰이는 같은 구조-assignability 체크.

Conditional 타입이 standard library 가 computed 타입 표현하는 법 — `ReturnType`, `Parameters`, `Awaited`, `NonNullable` 다 내부적으로 conditional 타입. 읽을 수 있게 되면 TypeScript 의 대부분 고급 타입 library 읽을 수 있어.

Distribution 규칙 (미리보기)

체크된 타입 (T) 이 naked generic parameter 일 때, conditional 타입이 union 에 분배. `string | number` 에 적용된 type Wrap<T> = T extends unknown ? { value: T } : never 가 분배: Wrap<string> | Wrap<number> = { value: string } | { value: number }. 트랙 6 에서 다뤘어; 같은 규칙 적용.

Bracket 트릭 ([T] extends [X]) 이 필요할 때 distribution 비활성화. Union 이 나뉘지 말아야 할 yes/no 체크에 사용.

Conditional composing

Conditional 체인 가능: type Classify<T> = T extends string ? 'str' : T extends number ? 'num' : 'other'. Multi-arm switch 처럼 읽어 — 각 `: T extends ...` 가 다음 case.

Conditional 타입이 타입이 다른 타입에 반응하게 만드는 법. 사람들이 고급 TypeScript 와 연관짓는 대부분 '마법' 을 unlock — 근데 그냥 타입-레벨 ternary, 그 이상 신비롭지 않아.

Code

Conditional 타입 — 체크와 체인·typescript
// 기본 conditional.
type IsString<T> = T extends string ? true : false;
type A = IsString<'hi'>;       // true
type B = IsString<42>;         // false

// Multi-arm chain.
type Classify<T> =
  T extends string ? 'str' :
  T extends number ? 'num' :
  T extends boolean ? 'bool' :
  'other';

type X = Classify<'hi'>;       // 'str'
type Y = Classify<true>;       // 'bool'
type Z = Classify<unknown[]>;  // 'other'

// Standard library 스타일 — ReturnType, 단순화.
type MyReturnType<F> = F extends (...args: any[]) => infer R ? R : never;
type G = MyReturnType<() => string>;       // string
type H = MyReturnType<(x: number) => User>; // User

External links

Exercise

T 가 배열이면 T 의 element 타입, 아니면 T 자체 반환하는 type ArrayElement<T> 써. ArrayElement<string[]>string; ArrayElement<number>number 여야. Conditional 타입 + infer 패턴 (다음 lesson 미리보기) 써.
Hint
type ArrayElement<T> = T extends (infer E)[] ? E : T. T 가 배열 모양 match 할 때 infer E 가 element 타입 캡처.

Progress

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

댓글 0

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

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