TypeScript 4.6 satisfies 연산자로 타입 체크 개선하기

문제 상황

설정 객체를 다루는 코드에서 타입 안정성 문제가 있었다. as const를 쓰면 너무 좁은 타입이 되고, 타입 단언을 쓰면 실수를 놓치기 쉬웠다.

const routes = {
  home: '/',
  user: '/user',
  admin: '/admim' // 오타 발견 못함
} as Routes;

const path = routes.home; // string으로 추론됨

satisfies 연산자

TypeScript 4.6에서 추가된 satisfies 연산자를 도입했다. 타입 체크는 하되 원래 타입 추론을 유지한다.

interface Routes {
  [key: string]: `/${string}`;
}

const routes = {
  home: '/',
  user: '/user',
  admin: '/admim' // 템플릿 리터럴 타입으로 검증
} satisfies Routes;

const path = routes.home; // '/' 리터럴 타입 유지

적용 사례

컬러 팔레트 정의에서 특히 유용했다.

type HexColor = `#${string}`;
type ColorPalette = Record<string, HexColor | { light: HexColor; dark: HexColor }>;

const colors = {
  primary: '#3b82f6',
  secondary: { light: '#a78bfa', dark: '#7c3aed' },
  error: '#ef4444'
} satisfies ColorPalette;

// 자동완성과 타입 추론이 정확하게 동작
const lightBg = colors.secondary.light;

타입 가드 없이도 구체적인 타입 정보를 유지하면서 제약 조건을 검증할 수 있어서, 설정 객체나 상수 정의에 적극 활용 중이다.

정리

  • as는 타입을 강제로 변환 (위험)
  • satisfies는 타입 검증 후 원본 유지 (안전)
  • 설정, 상수, 매핑 객체에 유용

TS 4.6 업그레이드 후 점진적으로 적용하고 있다.