TypeScript 3.8 const assertion으로 타입 추론 개선하기
문제 상황
코로나로 인한 재택근무 전환 후, 코드 리뷰에서 타입 관련 실수가 늘어났다. 특히 상수 객체를 다룰 때 타입이 넓게 추론되어 런타임 에러로 이어지는 케이스가 많았다.
const ROUTES = {
home: '/home',
profile: '/profile',
settings: '/settings'
};
// 타입이 { home: string, profile: string, settings: string }로 추론됨
type RouteKey = keyof typeof ROUTES; // OK
type RoutePath = typeof ROUTES[RouteKey]; // string (너무 넓음)
const assertion 도입
TypeScript 3.8에서 추가된 as const를 활용하면 리터럴 타입을 보존할 수 있다.
const ROUTES = {
home: '/home',
profile: '/profile',
settings: '/settings'
} as const;
type RoutePath = typeof ROUTES[keyof typeof ROUTES];
// "/home" | "/profile" | "/settings" (정확한 유니온 타입)
배열에도 유용하게 사용했다.
const STATUS_LIST = ['pending', 'approved', 'rejected'] as const;
type Status = typeof STATUS_LIST[number];
// "pending" | "approved" | "rejected"
function updateStatus(status: Status) {
// 타입 안전성 확보
}
실제 적용 사례
API 응답 코드 처리 로직에서 효과를 봤다.
const API_ERROR_CODES = {
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404
} as const;
type ErrorCode = typeof API_ERROR_CODES[keyof typeof API_ERROR_CODES];
function handleError(code: ErrorCode) {
// 401 | 403 | 404만 허용
}
결론
const assertion은 별도의 타입 정의 없이도 정확한 타입 추론을 가능하게 한다. 재택근무 환경에서 타입 안정성을 높이는 데 실질적인 도움이 되었다. 팀 코딩 컨벤션에 추가했다.