티스토리 뷰

이 글에서는 TypeScript에서 유니온 타입을 선언하는 다양한 방법을 소개합니다. 이를 통해 타입 시스템을 최대한 활용하여 더 안정적이고 읽기 쉬운 코드를 작성할 수 있을 것입니다.

 

1. 기본적인 유니온 타입 선언

가장 기본적인 유니온 타입은 파이프(|) 연산자를 사용하여 여러 타입을 결합하는 것입니다.

type StringOrNumber = string | number;

let value: StringOrNumber;
value = "hello";  // OK
value = 42;       // OK
value = true;     // Error: Type 'boolean' is not assignable to type 'string | number'.

 

StringOrNumber 타입은 문자열 또는 숫자만 허용합니다. 이와 같은 유니온 타입은 함수 인자나 변수에 다중 타입을 허용할 때 유용합니다.

 

2. 문자열 리터럴 유니온 타입

유니온 타입은 특정 문자열 값만 허용하고자 할 때도 사용할 수 있습니다. 이를 통해 허용된 값만 변수에 할당하도록 강제할 수 있습니다.

type Status = "idle" | "loading" | "success" | "error";

let currentStatus: Status;
currentStatus = "loading";  // OK
currentStatus = "completed"; // Error: Type '"completed"' is not assignable to type 'Status'.

 

이 방법은 상태 관리에서 많이 사용되며, 잘못된 문자열을 사용하지 않도록 도와줍니다.

 

3. 배열을 기반으로 유니온 타입 생성

배열의 요소들을 기반으로 유니온 타입을 생성할 수 있습니다. 

const statuses = ["idle", "loading", "success", "error"] as const;

type StatusType = (typeof statuses)[number];

let status: StatusType;
status = "success"; // OK
status = "failed";  // Error: Type '"failed"' is not assignable to type 'StatusType'.

 

 

as const를 사용함으로써, 이 배열의 요소들이 리터럴 타입으로 고정됩니다.

  • 즉, statuses의 요소들은 단순한 string[] 타입이 아니라, 각각 "idle", "loading", "success", "error"로 고정된 읽기 전용 배열(readonly ["idle", "loading", "success", "error"])이 됩니다.
  • as const를 사용하지 않으면, TypeScript는 이 배열을 string[] 타입으로 간주하여 각 요소의 타입을 구체적으로 알 수 없게 됩니다.

4. 조건부 타입을 활용한 유니온 타입

조건부 타입(Conditional Types)을 활용하면 입력된 타입에 따라 유니온 타입을 생성할 수 있습니다.

type TypeName<T> = T extends string
  ? "string"
  : T extends number
  ? "number"
  : "object";

type T1 = TypeName<string>;  // "string"
type T2 = TypeName<number>;  // "number"
type T3 = TypeName<boolean>; // "object"

 

제네릭 타입 파라미터 T를 받아, T의 실제 타입에 따라 다른 문자열 리터럴 타입을 반환합니다.

 

5. keyof와 타입 매핑을 통한 유니온 타입

keyof 키워드를 사용하면 객체 타입의 키들을 유니온 타입으로 추출할 수 있습니다.

type User = {
  id: number;
  name: string;
  age: number;
};

type UserKeys = keyof User; // "id" | "name" | "age"

let key: UserKeys;
key = "name"; // OK
key = "address"; // Error: Type '"address"' is not assignable to type 'UserKeys'.

 

중첩된 객체일때는 아래와 같이 유니온 타입을 추출할 수 있습니다.

type User = {
  id: number;
  name: string;
  status: {
    active: boolean;
    lastLogin: Date;
  };
  address: {
    street: string;
    city: string;
    zipCode: string | number;
  };
};

// 1. 최상위 레벨의 키들에 대한 유니온 타입
type TopLevelKeys = keyof User; // 'id' | 'name' | 'status' | 'address'

// 2. 중첩된 'status' 객체의 키들에 대한 유니온 타입
type StatusKeys = keyof User['status']; // 'active' | 'lastLogin'

// 3. 중첩된 'address' 객체의 키들에 대한 유니온 타입
type AddressKeys = keyof User['address']; // 'street' | 'city' | 'zipCode'

 

6. Extract와 Exclude를 활용한 유니온 타입 조작

TypeScript의 유틸리티 타입인 Extract와 Exclude를 사용하면 유니온 타입에서 특정 타입을 추출하거나 제외할 수 있습니다.

type Status = "idle" | "loading" | "success" | "error";

type ActiveStatus = Extract<Status, "loading" | "success">; // "loading" | "success"
type InactiveStatus = Exclude<Status, "loading" | "success">; // "idle" | "error"

 

이 방법을 통해 유니온 타입의 일부를 추출하거나, 특정 타입만 제외한 새로운 유니온 타입을 만들 수 있습니다.

 

결론

오늘은 유니온 타입을 다양하게 선언하는 방법에 대해서 알아보았습니다. TypeScript의 유니온 타입은 다양한 타입을 하나로 결합할 수 있는 강력한 기능입니다. 유니온 타입을 활용하면 타입 안전성을 유지하면서도 유연한 코드를 작성할 수 있습니다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
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 31
글 보관함