TypeScript 5.0 satisfies 연산자로 타입 안정성 높이기
문제 상황
프로젝트에서 API 엔드포인트 설정 객체를 관리하는데, 타입 안정성과 자동완성 사이에서 고민이 있었다. as const를 쓰면 타입이 너무 좁아지고, 일반 타입 선언만 하면 오타 검증이 안 됐다.
const routes = {
user: '/api/user',
products: '/api/products',
orders: '/api/order' // 오타가 있어도 컴파일 통과
};
satisfies 연산자
TypeScript 5.0에서 추가된 satisfies를 적용했다. 타입 제약을 검증하면서도 원래 타입 추론을 유지한다.
type Routes = Record<string, `${string}`>;
const routes = {
user: '/api/user',
products: '/api/products',
orders: '/api/orders'
} satisfies Routes;
// 타입 추론 유지됨
routes.user // string literal '/api/user'
실전 활용
컴포넌트 props 기본값 정의에 특히 유용했다.
type ButtonProps = {
variant: 'primary' | 'secondary';
size: 'sm' | 'md' | 'lg';
};
const defaultProps = {
variant: 'primary',
size: 'md'
} satisfies Partial<ButtonProps>;
// 자동완성과 타입 체크 모두 동작
defaultProps.variant // 'primary' (리터럴 타입)
정리
as는 타입을 강제로 변환하고, satisfies는 제약만 검증한다. 설정 객체나 상수 정의할 때 타입 안정성을 높이는데 효과적이었다. 팀원들에게도 공유해서 점진적으로 적용 중이다.