TypeScript 4.9 satisfies 연산자로 타입 안전성 높이기
문제 상황
프로젝트에서 설정 객체를 정의할 때 타입 안전성과 자동완성을 모두 확보하기 어려웠다. as const를 쓰면 타입은 안전하지만 구조 검증이 안 되고, 타입 단언을 쓰면 추론이 깨졌다.
type Config = {
apiUrl: string;
timeout: number;
};
// as로 단언하면 추론이 string으로 넓어짐
const config: Config = {
apiUrl: "https://api.example.com",
timeout: 3000
};
// as const는 리터럴 타입이지만 Config 구조 검증 안 됨
const config2 = {
apiUrl: "https://api.example.com",
timout: 3000 // 오타 감지 못함
} as const;
satisfies 연산자
TypeScript 4.9에서 추가된 satisfies는 이 문제를 해결했다. 타입을 검증하면서도 추론은 유지한다.
const config = {
apiUrl: "https://api.example.com",
timeout: 3000
} satisfies Config;
// config.apiUrl은 string이 아닌 "https://api.example.com" 타입
// 동시에 Config 구조를 만족하는지 컴파일 타임에 검증됨
실무 적용
라우트 설정에서 유용하게 썼다. 각 라우트의 path는 리터럴 타입으로 유지하면서도 전체 구조는 검증할 수 있었다.
type Route = {
path: string;
component: string;
auth: boolean;
};
const routes = [
{
path: "/dashboard",
component: "Dashboard",
auth: true
},
{
path: "/login",
component: "Login",
auth: false
}
] satisfies Route[];
// routes[0].path는 "/dashboard" 타입
// 타입 가드나 switch 문에서 정확한 추론 가능
정리
TypeScript 4.9으로 업그레이드 후 설정 객체와 상수 정의에 satisfies를 적용했다. as 키워드를 남발하던 코드들이 더 안전해졌고, 타입 추론도 개선됐다. 프로젝트 전반에 점진적으로 적용 중이다.