TypeScript 고급 타입 | Union, Intersection, Literal 타입
이 글의 핵심
TypeScript 고급 타입에 대한 실전 가이드입니다. Union, Intersection, Literal 타입 등을 예제와 함께 상세히 설명합니다.
들어가며
TypeScript의 고급 타입을 쓰면, 값에 붙는 명찰을 더 세밀하게 나눌 수 있습니다. “문자열 또는 숫자만 허용”처럼 조합·제한을 표현하면, 런타임(프로그램이 실제로 실행되는 때) 전에 의도를 문서처럼 고정할 수 있습니다.
1. Union 타입
개념
Union 타입은 여러 타입 중 하나일 수 있는 타입입니다.
// 문법: 타입1 | 타입2 | 타입3
let value: string | number;
value = "문자열"; // ✅
value = 123; // ✅
// value = true; // ❌ 에러
실전 예제
// 함수 매개변수
function printId(id: string | number) {
console.log(`ID: ${id}`);
}
printId(101); // ID: 101
printId("USER001"); // ID: USER001
// 배열
let mixedArray: (string | number)[] = [1, "two", 3, "four"];
// 함수 반환 타입
function getResult(success: boolean): string | null {
return success ? "성공" : null;
}
타입 가드 (Type Guard)
Union 타입을 사용할 때는 타입 가드로 타입을 좁혀서(narrowing) 안전하게 사용해야 합니다:
function processValue(value: string | number) {
// typeof 연산자로 런타임에 타입 체크
// TypeScript 컴파일러는 이를 인식하고 타입을 좁혀줌 (Type Narrowing)
if (typeof value === "string") {
// ✅ 이 블록 안에서 value는 string 타입으로 좁혀짐
// string 전용 메서드를 안전하게 사용 가능
console.log(value.toUpperCase()); // 대문자로 변환
console.log(value.length); // 문자열 길이
console.log(value.trim()); // 공백 제거
} else {
// ✅ else 블록에서는 value가 number 타입으로 좁혀짐
// (string이 아니면 number이므로)
// number 전용 메서드를 안전하게 사용 가능
console.log(value.toFixed(2)); // 소수점 2자리로 포맷
console.log(value * 2); // 숫자 연산
console.log(value.toExponential()); // 지수 표기법
}
}
processValue("hello"); // HELLO, 5
processValue(3.14159); // 3.14, 6.28318
타입 가드가 없다면:
function processValueBad(value: string | number) {
// ❌ 컴파일 에러: string | number에는 toUpperCase()가 없음
// console.log(value.toUpperCase());
// TypeScript는 value가 string인지 number인지 모르므로
// string 전용 메서드 호출을 허용하지 않음
// ❌ 컴파일 에러: string | number에는 toFixed()가 없음
// console.log(value.toFixed(2));
// ✅ 타입 가드 없이는 공통 메서드만 사용 가능
console.log(value.toString()); // 둘 다 toString() 있음
console.log(value.valueOf()); // 둘 다 valueOf() 있음
}
다양한 타입 가드 방법:
// 1. typeof 타입 가드 (원시 타입)
function format(value: string | number | boolean) {
if (typeof value === "string") {
return value.toUpperCase();
} else if (typeof value === "number") {
return value.toFixed(2);
} else {
return value ? "참" : "거짓";
}
}
// 2. instanceof 타입 가드 (클래스 인스턴스)
function handleError(error: Error | string) {
if (error instanceof Error) {
// Error 객체의 프로퍼티 접근 가능
console.log(error.message);
console.log(error.stack);
} else {
// string
console.log(error);
}
}
// 3. in 연산자 타입 가드 (프로퍼티 존재 확인)
type Dog = { bark: () => void };
type Cat = { meow: () => void };
function makeSound(animal: Dog | Cat) {
if ("bark" in animal) {
// animal은 Dog 타입으로 좁혀짐
animal.bark();
} else {
// animal은 Cat 타입으로 좁혀짐
animal.meow();
}
}
// 4. 사용자 정의 타입 가드 (Type Predicate)
function isString(value: unknown): value is string {
return typeof value === "string";
}
function process(value: unknown) {
if (isString(value)) {
// value는 string으로 좁혀짐
console.log(value.toUpperCase());
}
}
2. Intersection 타입
개념
Intersection 타입은 여러 타입을 모두 만족하는 타입입니다.
// 문법: 타입1 & 타입2 & 타입3
type Person = {
name: string;
age: number;
};
type Employee = {
employeeId: string;
department: string;
};
type Staff = Person & Employee;
const staff: Staff = {
name: "홍길동",
age: 30,
employeeId: "E001",
department: "개발팀"
};
실전 예제
// 믹스인 패턴
type Timestamped = {
createdAt: Date;
updatedAt: Date;
};
type User = {
id: string;
name: string;
email: string;
};
type UserWithTimestamp = User & Timestamped;
const user: UserWithTimestamp = {
id: "U001",
name: "홍길동",
email: "[email protected]",
createdAt: new Date(),
updatedAt: new Date()
};
3. Literal 타입
개념
Literal 타입은 정확한 값을 타입으로 지정합니다.
// 문자열 리터럴
let direction: "left" | "right" | "up" | "down";
direction = "left"; // ✅
// direction = "top"; // ❌ 에러
// 숫자 리터럴
let diceRoll: 1 | 2 | 3 | 4 | 5 | 6;
diceRoll = 3; // ✅
// diceRoll = 7; // ❌ 에러
// 불리언 리터럴
let isTrue: true;
isTrue = true; // ✅
// isTrue = false; // ❌ 에러
실전 예제
// HTTP 메서드
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
function request(url: string, method: HttpMethod) {
console.log(`${method} ${url}`);
}
request("/api/users", "GET"); // ✅
// request("/api/users", "PATCH"); // ❌ 에러
// 상태 관리
type Status = "idle" | "loading" | "success" | "error";
interface ApiState {
status: Status;
data: any;
error: string | null;
}
const state: ApiState = {
status: "loading",
data: null,
error: null
};
4. Type Alias
개념
Type Alias는 타입에 이름을 붙입니다.
// 기본 사용
type UserId = string;
type Age = number;
let id: UserId = "U001";
let age: Age = 25;
// 객체 타입
type User = {
id: UserId;
name: string;
age: Age;
email: string;
};
const user: User = {
id: "U001",
name: "홍길동",
age: 25,
email: "[email protected]"
};
함수 타입
// 함수 타입 정의
type MathOperation = (a: number, b: number) => number;
const add: MathOperation = (a, b) => a + b;
const subtract: MathOperation = (a, b) => a - b;
const multiply: MathOperation = (a, b) => a * b;
console.log(add(10, 5)); // 15
console.log(subtract(10, 5)); // 5
5. Type Narrowing
typeof 가드
function processInput(input: string | number) {
if (typeof input === "string") {
// input은 string
return input.toUpperCase();
} else {
// input은 number
return input.toFixed(2);
}
}
instanceof 가드
class Dog {
bark() {
console.log("멍멍!");
}
}
class Cat {
meow() {
console.log("야옹!");
}
}
function makeSound(animal: Dog | Cat) {
if (animal instanceof Dog) {
animal.bark();
} else {
animal.meow();
}
}
makeSound(new Dog()); // 멍멍!
makeSound(new Cat()); // 야옹!
in 연산자
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird) {
if ("swim" in animal) {
animal.swim();
} else {
animal.fly();
}
}
사용자 정의 타입 가드
interface User {
id: string;
name: string;
}
interface Admin {
id: string;
name: string;
permissions: string[];
}
// 타입 가드 함수
function isAdmin(user: User | Admin): user is Admin {
return "permissions" in user;
}
function greet(user: User | Admin) {
if (isAdmin(user)) {
console.log(`관리자 ${user.name}, 권한: ${user.permissions.join(", ")}`);
} else {
console.log(`사용자 ${user.name}`);
}
}
6. 실전 예제
예제 1: API 응답 타입
type ApiResponse<T> =
| { success: true; data: T }
| { success: false; error: string };
async function fetchUser(id: string): Promise<ApiResponse<User>> {
try {
const response = await fetch(`/api/users/${id}`);
const data = await response.json();
return { success: true, data };
} catch (error) {
return { success: false, error: "사용자를 찾을 수 없습니다" };
}
}
// 사용
const result = await fetchUser("U001");
if (result.success) {
console.log("사용자:", result.data.name);
} else {
console.error("에러:", result.error);
}
예제 2: 상태 머신
type State =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: any }
| { status: "error"; error: string };
function handleState(state: State) {
switch (state.status) {
case "idle":
console.log("대기 중");
break;
case "loading":
console.log("로딩 중...");
break;
case "success":
console.log("데이터:", state.data);
break;
case "error":
console.error("에러:", state.error);
break;
}
}
// 사용
handleState({ status: "idle" });
handleState({ status: "loading" });
handleState({ status: "success", data: { name: "홍길동" } });
handleState({ status: "error", error: "네트워크 에러" });
7. 자주 하는 실수
실수 1: Union 타입 오해
// ❌ 잘못된 사용
function getLength(value: string | number) {
return value.length; // 에러: number에는 length 없음
}
// ✅ 올바른 사용
function getLength(value: string | number) {
if (typeof value === "string") {
return value.length;
}
return value.toString().length;
}
실수 2: Intersection 타입 충돌
// ❌ 충돌하는 타입
type A = { value: string };
type B = { value: number };
type C = A & B; // value는 never 타입
// ✅ 올바른 사용
type A = { name: string };
type B = { age: number };
type C = A & B; // { name: string; age: number }
정리
핵심 요약
- Union:
A | B(또는) - Intersection:
A & B(그리고) - Literal: 정확한 값
- Type Alias: 타입 이름 지정
- Type Narrowing: 타입 좁히기
다음 단계
- TypeScript 인터페이스
- TypeScript 제네릭
- TypeScript 유틸리티 타입
관련 글
- C++ Union과 Variant |
- TypeScript 인터페이스 | Interface 완벽 가이드
- TypeScript 제네릭 | Generics 완벽 가이드
- C++ Algorithm Set |
- C++ std::variant vs union |