TypeScript 4.8 satisfies 연산자로 타입 안정성 높이기
문제 상황
설정 객체를 다루는 코드에서 타입 안정성을 확보하기 어려웠다. as const를 쓰면 타입은 정확해지지만 구조 검증이 안 되고, 타입 단언을 쓰면 추론이 넓어져서 자동완성이 제대로 동작하지 않았다.
const config = {
endpoint: '/api/users',
method: 'GET',
timeout: 3000
} as Config; // 타입은 맞지만 추론이 Config로 넓어짐
satisfies 연산자
TypeScript 4.8에서 추가된 satisfies를 사용하니 해결됐다. 타입 체크는 하되 추론은 유지한다.
type RouteConfig = {
path: string;
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
timeout?: number;
};
const userRoute = {
path: '/api/users',
method: 'GET',
timeout: 3000
} satisfies RouteConfig;
// userRoute.method의 타입은 'GET'으로 좁혀짐
// RouteConfig 구조는 검증됨
실전 활용
환경별 설정 객체에 적용했다.
type Environment = {
apiUrl: string;
features: Record<string, boolean>;
};
const environments = {
dev: {
apiUrl: 'http://localhost:3000',
features: { newUI: true }
},
prod: {
apiUrl: 'https://api.example.com',
features: { newUI: false }
}
} satisfies Record<string, Environment>;
// environments.dev.apiUrl은 string literal로 추론
// 잘못된 키 접근 시 컴파일 에러
결론
타입 단언의 위험성 없이 제약을 걸 수 있어서 만족스러웠다. 특히 설정 객체나 상수 정의에서 유용하게 쓰고 있다.