TypeScript 5.3의 Import Attributes로 JSON 모듈 타입 안전하게 다루기
배경
프로젝트에서 다국어 지원을 위해 JSON 파일로 번역 데이터를 관리하고 있었다. TypeScript 5.3으로 업그레이드하면서 Import Attributes 문법이 정식 지원되어 기존 코드를 마이그레이션했다.
기존 방식의 문제
// 기존: assert 문법 (deprecated)
import translations from './locales/ko.json' assert { type: 'json' };
// 또는 타입 단언
import translations from './locales/ko.json';
const data = translations as Record<string, string>;
assert 문법은 TC39에서 deprecated 되었고, 타입 단언은 런타임 안전성을 보장하지 못했다.
Import Attributes 적용
TypeScript 5.3부터 with 키워드를 사용하는 Import Attributes를 지원한다.
// tsconfig.json
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true
}
}
// 새로운 문법
import translations from './locales/ko.json' with { type: 'json' };
// 타입 추론 자동 적용
translations.common.title; // 타입 체크 O
적용 결과
- JSON 파일 변경 시 타입 체크가 즉시 작동
- 불필요한 타입 단언 제거
- 번들러(Vite)와의 호환성 확인
번역 파일이 30개 이상인 프로젝트에서 타입 안전성이 크게 개선되었다. ESLint에서 deprecated 경고도 사라졌다.
주의사항
- Node.js 20.10+ 또는 번들러 지원 필요
resolveJsonModule옵션 필수- 기존 assert 문법은 5.x대에서도 당분간 동작하지만 마이그레이션 권장
표준 문법으로 전환하면서 향후 유지보수성도 확보할 수 있었다.