TypeScript는 다른 유형을 변환하고 조작하는 다양한 내장 유틸리티 유형 세트를 제공합니다. 이러한 도구를 이해하면 바퀴를 다시 개발하지 않고도 더욱 표현력이 풍부하고 유형이 안전한 코드를 작성할 수 있습니다.
속성 수정 유형
이러한 유형은 객체 속성의 선택성, 변경 가능성 및 요구 사항을 수정합니다.
interface User {
id: number;
name: string;
email?: string;
}
type PartialUser = Partial<User>;
// { id?: number; name?: string; email?: string; }
type RequiredUser = Required<User>;
// { id: number; name: string; email: string; }
type ImmutableUser = Readonly<User>;
// { readonly id: number; readonly name: string; readonly email?: string; }
| 유형 | 효과 | 공용 |
|---|---|---|
부분<T> | 모든 속성은 선택사항 | 패치 요청 본문 |
필수<T> | 모든 속성이 필요합니다 | 양식 제출 확인 |
읽기 전용<T> | 모든 속성은 읽기 전용 | 구성 개체 |
부분은 클라이언트가 필드의 하위 집합을 보낼 수 있어야 하는 API 업데이트 작업에 특히 유용합니다.
async function updateUser(id: number, changes: Partial<User>): Promise<User> {
const res = await fetch(`/api/users/${id}`, {
method: 'PATCH',
body: JSON.stringify(changes),
});
return res.json();
}
속성 선택 유형
‘Pick’ 및 ‘Omit’을 사용하면 유형에서 특정 속성을 선택하거나 제외할 수 있습니다.
type UserView = Pick<User, 'id' | 'name'>;
// { id: number; name: string; }
type UserWithoutEmail = Omit<User, 'email'>;
// { id: number; name: string; }
‘생략’은 민감한 필드를 제거하는 데 이상적입니다.
type SafeUser = Omit<User, 'password' | 'token'>;
이러한 유형은 세밀한 제어를 위해 교차 유형과 잘 구성됩니다.
type UserProfile = Pick<User, 'name' | 'email'> & { bio?: string };
통합 필터링 유형
‘추출’ 및 ‘제외’는 유형 호환성을 기준으로 공용체 멤버를 필터링합니다.
type Status = 'idle' | 'loading' | 'success' | 'error';
type ActiveStatus = Exclude<Status, 'idle'>;
// 'loading' | 'success' | 'error'
type ApiEvent =
| { type: 'user.created'; user: User }
| { type: 'user.deleted'; id: number }
| { type: 'error'; message: string };
type UserEvents = Extract<ApiEvent, { type: `user.${string}` }>;
// { type: 'user.created'; user: User } | { type: 'user.deleted'; id: number }
NonNullable<T>은 유형에서 null 및 undefine을 제거합니다.
type Maybe = string | null | undefined;
type Definite = NonNullable<Maybe>; // string
객체 구성 유형
Record<K, T>는 지정된 키 및 값 유형을 사용하여 객체 유형을 생성합니다.
type UserMap = Record<string, User>;
type RolePermissions = Record<'admin' | 'editor' | 'viewer', string[]>;
const permissions: RolePermissions = {
admin: ['create', 'read', 'update', 'delete'],
editor: ['create', 'read', 'update'],
viewer: ['read'],
};
함수 및 클래스 유형
이러한 유형은 함수 서명에서 정보를 추출합니다.
type Fn = (a: string, b: number) => boolean;
type Params = Parameters<Fn>; // [string, number]
type Ret = ReturnType<Fn>; // boolean
type FirstParam = Params[0]; // string
Awaited<T>는 Promise 유형을 재귀적으로 풀어냅니다.
type AsyncResult = Awaited<Promise<Promise<string>>>; // string
InstanceType<T>는 생성자에서 인스턴스 유형을 추출합니다.
class Service { /* ... */ }
type ServiceInstance = InstanceType<typeof Service>; // Service
구성 패턴
유틸리티 유형을 결합하면 표현적인 유형 정의가 생성됩니다.
type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type UserUpdate = Optional<User, 'email'>;
// id and name required, email optional
깊은 부분 객체의 경우 재귀 매핑 유형이 작업을 수행합니다.
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
TypeScript 유틸리티 유형을 마스터하면 상용구가 줄어들고 유형 안전성이 향상되며 코드의 표현력이 향상됩니다. ‘Partial’, ‘Pick’ 및 ‘Record’로 시작한 다음 유형 수준 프로그래밍 요구 사항이 증가함에 따라 점차 고급 유형을 통합하십시오.

