TypeScript 5.3의 Import Attributes로 JSON 모듈 타입 안전하게 불러오기
문제 상황
다국어 지원을 위해 JSON 파일로 번역 데이터를 관리하고 있었는데, import 시 타입이 any로 추론되는 문제가 있었다.
import translations from './locales/ko.json';
// translations의 타입이 any로 추론됨
기존에는 resolveJsonModule 옵션을 켜고 사용했지만, 대규모 JSON 파일의 경우 타입 체킹 성능이 떨어지는 이슈도 있었다.
TypeScript 5.3 Import Attributes
TypeScript 5.3에서 TC39 Stage 3 제안인 Import Attributes를 정식 지원하기 시작했다. 이전의 Import Assertions를 대체하는 문법이다.
import translations from './locales/ko.json' with { type: 'json' };
tsconfig.json에서 설정을 조정했다.
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true
}
}
타입 안전성 확보
제네릭 타입을 활용해 JSON 스키마를 정의했다.
interface TranslationSchema {
common: Record<string, string>;
errors: Record<string, string>;
}
import koTranslations from './locales/ko.json' with { type: 'json' };
const translations: TranslationSchema = koTranslations;
Bundler(Vite, Webpack 5)들도 이 문법을 지원하기 시작해서 런타임 에러 없이 바로 적용할 수 있었다.
결과
- JSON import 시 명시적인 타입 선언으로 안전성 확보
- IDE 자동완성 지원으로 개발 생산성 향상
- 번역 키 오타로 인한 런타임 에러 사전 방지
아직 Stage 3 제안이라 향후 문법이 변경될 가능성은 있지만, 표준화 방향으로 가고 있어 도입해도 무방하다고 판단했다.