TypeScript导入JSON实现i18n时翻译Hook索引类型报错
报错原因
报错的核心是两处类型不匹配:
useTranslate定义的入参key为宽泛的string类型,但i18n语言包对象的key是固定字面量联合类型,TypeScript不允许任意字符串作为索引访问固定结构的对象- 现有i18n类型分别独立推导DE、EN语言包的key,没有强制约束不同语言包的key完全一致,后续新增翻译项时容易出现单语言缺项的问题
修复方案
1. 优化i18n入口的类型定义
修改i18n/index.tsx,提取统一的翻译结构和合法key类型,同时强制所有语言包结构和基准语言保持一致:
import DE from './DE.json'; import EN from './EN.json'; // 若LangType已在状态类型文件定义,直接导入复用即可,无需重复声明 type LangType = 'EN' | 'DE'; // 以英文包为基准推导翻译项结构 type TranslationSchema = typeof EN; // 提取所有合法翻译key的联合类型,例如 'featured' | 'replies' export type TranslationKey = keyof TranslationSchema; // 约束i18n配置:所有语言必须和基准语言结构完全一致,避免漏翻译 export type i18nProps = Record<LangType, TranslationSchema>; const i18n: i18nProps = { DE, EN }; export default i18n;
2. 修正useTranslate Hook的类型
将翻译函数的入参类型从string改为提取出的TranslationKey,从根源解决索引类型不匹配问题,同时获得调用时的类型校验和自动提示:
import { useAppSelector } from '.'; import i18n, { TranslationKey } from '../i18n'; function useTranslate(): (key: TranslationKey) => string { const lang = useAppSelector((state) => state.lang); return (key) => { return i18n[lang][key]; }; } export default useTranslate;
3. 确认TS配置支持JSON类型推导
在tsconfig.json中开启以下配置,保证导入JSON文件时能获得准确的类型推导:
{ "compilerOptions": { "resolveJsonModule": true, "strict": true } }
修改完成后原有报错会直接消除,同时在组件中调用translate()时,如果传入不存在的翻译key,TypeScript会直接抛出类型错误,避免线上出现翻译缺失的问题。
内容的提问来源于stack exchange,提问作者Pingolin
相关产品推荐
相关产品推荐

