| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 |
Tags
- 제어컴포넌트
- parent padding
- CustomHook
- twoarrow
- transition
- accordian
- 문제해결
- tailwindCSS
- ignore padding
- react
- 화살표2개
- 서초구보건소 #무료CPR교육
- useQueryClient
- vite
- 부모패딩
- createPortal
- Carousel
- QueryClient
- 이즐 #ezl #욕나오는 #교통카드
- DOM
- 부모요소의 패딩 무시
- es6
- 조건부스타일
- 리액트
- BlockFormattingContext
- alias설정
- ?? #null병합연산자
- 함수형프로그래밍
- BFC
- debouncing
Archives
- Today
- Total
프론트엔드 첫걸음
Typescript 분배 규칙 본문
타입스크립트의 분배 규칙(distributive conditional types)은 조건부 타입(T extends U ? X : Y)을 정의할 때 제네릭 매개변수에 유니언 타입이 들어오면, 그 유니언 타입의 각 멤버에 대해 개별적으로 조건이 적용되는 동작을 말함.
1. 기본 개념
type Example<T> = T extends number ? 'num' : 'other';
- T가 제네릭이 아닌 고정된 타입이면 그대로 조건 판별:
type A = Example<number>; // 'num'
type B = Example<string>; // 'other'
- T가 유니언 타입이면, 각 멤버별로 조건을 적용한 후 결과를 다시 유니언으로 합침:
type C = Example<number | string>;
// 처리 과정:
// 1. number → 'num'
// 2. string → 'other'
// 결과: 'num' | 'other'
이게 분배(distribution) 동작입니다.
2. 분배 규칙이 동작하는 조건
- 제네릭 타입 매개변수가 조건문의 좌변에 그대로 사용되어야 함
- T extends U ? X : Y 형태일 때만 자동 분배됨
예:
type Distributed<T> = T extends number ? 'num' : 'other';
type D1 = Distributed<number | string>; // 'num' | 'other'
3. 분배를 막는 방법
T를 한 번 래핑하면 분배가 일어나지 않음:
type NonDistributed<T> = [T] extends [number] ? 'num' : 'other';
type D2 = NonDistributed<number | string>;
// [number | string] extends [number] → false
// 결과: 'other'
이 방법을 **"분배 방지(disable distribution)"**라고 합니다.
4. 활용 예시
4.1 Exclude 타입
type Exclude<T, U> = T extends U ? never : T;
type E1 = Exclude<'a' | 'b' | 'c', 'a'>;
// 처리 과정:
// 'a' extends 'a' → never
// 'b' extends 'a' → 'b'
// 'c' extends 'a' → 'c'
// 결과: 'b' | 'c'
4.2 Extract 타입
type Extract<T, U> = T extends U ? T : never;
type E2 = Extract<'a' | 'b' | 'c', 'a' | 'b'>;
// 결과: 'a' | 'b'
5. 핵심 정리
- 유니언 타입이 제네릭에 들어오면, 조건부 타입이 멤버별로 적용된다.
- 조건문의 좌변에 T가 직접 와야 분배됨.
- 분배를 막으려면 T를 [T]처럼 튜플 등으로 감싸면 된다.
- Exclude, Extract 같은 기본 유틸리티 타입도 이 규칙을 기반으로 동작한다.
'개발 공부 > Typescript' 카테고리의 다른 글
| Parameter Properties (0) | 2025.07.05 |
|---|---|
| 웹스톰 타입스크립트 파일 실행하기 (0) | 2024.04.27 |
| type void (0) | 2024.02.23 |
| 객체 리터럴의 추가 속성 검사 (0) | 2024.02.23 |
| object를 enum처럼 사용하기 (0) | 2024.02.23 |