유니언 타입 (Union Types)
TypeScript에서 유니언 타입은 하나의 값이 여러 타입 중 하나일 수 있음을 표현한다.
집합 이론에서의 합집합(A ∪ B)
개념과 동일하며, |
기호를 사용한다.
1. 기본 사용법
유니언 타입을 정의할 때는 파이프 |
기호를 사용해 여러 타입을 나열한다.
ts
let userId: string | number;
userId = 1;
userId = "1";
userId = true; // 오류
userId = {}; // 오류
함수의 매개변수에도 적용할 수 있다
ts
// 함수
function printUserId(id: string | number) {
console.log(id);
}
printUserId("1");
printUserId(1);
printUserId({}); // 오류: string | number 아닌 빈 객체
2. Type Narrowing (타입 좁히기)
유니언 타입은 여러 타입이 가능하므로, 실제 실행 시점에서는 조건문 등을 사용해 타입을 좁혀야 한다.
ts
function processValue(value: number | string) {
if (typeof value === "string") {
// 문자열인 경우
return value.toUpperCase();
}
// 숫자인 경우
return value.toString().toUpperCase();
}
typeof
: 런타임에서 타입 체크toString()
: 숫자를 문자열로 변환toUpperCase()
: 문자열 메서드
3. 배열에 유니언 타입 적용
유니언 타입은 배열 요소에도 적용할 수 있다.
ts
let mixedValues: (string | number)[] = [];
mixedValues.push("100");
mixedValues.push(100);
mixedValues.push([]); // 오류
(string | number)[]
: 문자열과 숫자가 섞인 배열 가능string[] | number[]
: 전부 문자열 배열이거나 전부 숫자 배열만 가능
4. 리터럴 타입 (Literal Type)
리터럴 타입은 특정 값만 허용하는 타입이다.
ts
const toggle = (option: "on" | "off") => {
console.log(option);
};
toggle("on");
toggle("off");
toggle(true); // 오류
toggle(0); // 오류
ts
// 예시: 티셔츠 사이즈 타입
type Size = "xs" | "s" | "m" | "l" | "xl";
let tShirtSize: Size;
tShirtSize = "m";
tShirtSize = "xxl"; // 오류
// 함수
function serSize(size: Size) {
switch (size) {
case "xs":
console.log("아주 작음");
break;
case "s":
console.log("좀 작음");
break;
// ..
}
}
5. 타입 별칭 (Type Aliases)
유니언 타입을 자주 쓰는 경우, 타입 별칭을 만들어 재사용할 수 있다.
ts
type SuccessCode: 200 | 201 | 202;
type ErrorCode: 500 | 501 | 503;
let responseCode: SuccessCode | ErrorCode;
responseCode = 200; // OK
responseCode = 503; // OK
responseCode = 404; // 오류