Notice
Recent Posts
Recent Comments
Link
250x250
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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
- java
- 쿼리
- web
- 알고리즘
- 디자인 패턴
- 프론트엔드
- 자바스크립트
- 스프링
- JavaScript
- 프런트엔드
- 프로그래머스
- spring
- 오라클
- 코드테스트
- 미니정리
- node.js
- MySQL
- SQL
- 서버
- 데이터베이스
- jpa
- oracle
- Next.js
- 스프링부트
- 정리
- BACK-END
- 자바
- 백엔드
- 코드 테스트
- jsp
Archives
- Today
- Total
참치코더의 꿈 메모장
TypeScript / 서로소 유니언 미니 정리 본문
728x90

여러 형태로 구성된 타입을 하나의 큰 유니언 타입으로 묶되, 내부적으로 구분을 통해 정확하게 좁히는 패턴을 말한다.
서로소 유니언의 특징
1. 공통된 식별자 키가 있다.
2. 각 타입은 그 식별자에 서로 다른 값을 가지며 여러 타입이 유니언으로 묶여 있다.
3. switch문에서 자동으로 타입을 좁힌다.
4. 특정 키를 검사하는 순간 타입을 정확하게 추론한다.
5. 조건문 기반 Narrowing이 매우 직관적이다.
6. 실수 발생 가능성이 적으며 컴파일러의 보호를 받는다.
type Shape = {kind: "circle"; radius: number} |
{kind: "square"; size: number} |
{kind: "triangle"; width; height: number};
식별자: kind, circle/square/triangle은 서로 다른 값을 통해 구분한다.
|
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
|
type Shape =
{ kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "triangle"; width: number; height: number };
function getArea(shape: Shape){
switch (shape.kind){
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size * shape.size;
case "triangle":
return (shape.width * shape.height) / 2;
default:
const _exhaustive: never = shape;
return _exhaustive;
}
}
// 각 case 안에서 shape의 타입이 완벽하게 좁혀진다.
// 타입스크립트가 완전히 이해하고 자동으로 좁힘을 수행해준다.
// 새로운 타입이 추가되면 default에서 에러가 발생한다.
// 유지보수가 매우 쉬워진다.
|
cs |
728x90
'TypeScript' 카테고리의 다른 글
| TypeScript / 함수 타입 정리 (0) | 2025.12.02 |
|---|---|
| TypeScript / 타입 좁히기(Type Narrowing) 정리 (0) | 2025.11.27 |
| TypeScript / 타입 단언 정리 (0) | 2025.11.27 |
| TypeScript / 대수 타입, 타입 추론 정리 (0) | 2025.11.25 |
| TypeScript / 기본 타입 호환성, 객체 타입 호환성 정리 (0) | 2025.11.24 |
Comments