TypeScript 유틸리티 타입(Utility Types)은 기존 타입을 변환하는 내장 제네릭 타입들이다. 코드 중복 없이 타입을 재활용하고 변형할 수 있다.
Partial / Required / Readonly
typescript
interface User {
id: number;
name: string;
email: string;
}
// Partial<T>: 모든 속성을 선택적으로
type UpdateUser = Partial<User>;
// { id?: number; name?: string; email?: string }
// Required<T>: 모든 속성을 필수로
type StrictUser = Required<UpdateUser>;
// Readonly<T>: 모든 속성을 읽기 전용으로
const user: Readonly<User> = { id: 1, name: 'Alice', email: 'a@b.com' };
// user.name = 'Bob'; // Error: 읽기 전용 속성
Pick / Omit / Record
typescript
// Pick<T, K>: K 키만 선택
type UserPreview = Pick<User, 'id' | 'name'>;
// { id: number; name: string }
// Omit<T, K>: K 키를 제외
type PublicUser = Omit<User, 'email'>;
// { id: number; name: string }
// Record<K, V>: K 타입 키, V 타입 값의 객체
type RoleMap = Record<'admin' | 'user' | 'guest', number>;
const roles: RoleMap = { admin: 1, user: 2, guest: 3 };
typescript
type Status = 'active' | 'inactive' | 'banned' | 'pending';
// Exclude<T, U>: T에서 U에 할당 가능한 타입 제거
type ActiveStatus = Exclude<Status, 'banned' | 'inactive'>;
// 'active' | 'pending'
// Extract<T, U>: T에서 U에 할당 가능한 타입만 추출
type BadStatus = Extract<Status, 'banned' | 'inactive'>;
// 'banned' | 'inactive'
// NonNullable<T>: null, undefined 제거
type SafeString = NonNullable<string | null | undefined>;
// string
ReturnType / Parameters / InstanceType
typescript
function createUser(name: string, age: number): User { ... }
type UserFactory = typeof createUser;
type UserResult = ReturnType<UserFactory>; // User
type UserParams = Parameters<UserFactory>; // [string, number]
class ApiClient { baseUrl: string; ... }
type ClientInstance = InstanceType<typeof ApiClient>;
// ApiClient 인스턴스 타입
Awaited (TypeScript 4.5+)
typescript
// 프로미스 체인을 재귀적으로 언랩
type A = Awaited<Promise<string>>; // string
type B = Awaited<Promise<Promise<number>>>; // number
type C = Awaited<boolean | Promise<number>>; // boolean | number
관련 개념