TypeScript 4.7 satisfies 연산자로 타입 안정성 높이기
문제 상황
프로젝트에서 설정 객체를 다루다가 타입 문제에 부딪혔다. 특정 키는 string, 어떤 키는 number를 가져야 하는데 as const를 쓰면 너무 좁아지고, 타입 단언을 쓰면 안전성이 떨어졌다.
const config = {
apiUrl: "https://api.example.com",
timeout: 5000,
retries: 3
};
// as const를 쓰면 리터럴 타입으로 고정됨
// 타입 단언을 쓰면 실수를 잡아내지 못함
satisfies 연산자
TypeScript 4.7에서 추가된 satisfies 연산자가 이 문제를 깔끔하게 해결해줬다. 타입을 검증하면서도 타입 추론은 유지한다.
type Config = {
apiUrl: string;
timeout: number;
retries: number;
};
const config = {
apiUrl: "https://api.example.com",
timeout: 5000,
retries: 3
} satisfies Config;
// 타입 체크는 통과하면서도
// config.timeout은 number로 추론됨 (5000이 아니라)
실전 활용
라우트 설정에 적용해봤다. 각 라우트마다 권한이나 메타데이터가 달라서 유연성이 필요했는데, satisfies로 구조는 강제하면서 구체적인 타입은 보존할 수 있었다.
type Route = {
path: string;
auth: boolean;
roles?: string[];
};
const routes = {
home: { path: "/", auth: false },
dashboard: { path: "/dashboard", auth: true, roles: ["admin"] },
profile: { path: "/profile", auth: true }
} satisfies Record<string, Route>;
// routes.dashboard.roles는 string[] | undefined
// as const 없이도 정확한 타입 추론
정리
as 단언과 타입 추론 사이에서 고민할 필요가 줄었다. 특히 설정 객체나 상수 테이블처럼 구조는 검증하되 구체적인 값의 타입은 유지해야 할 때 유용하다.