react-i18next 搭配 typescript 缺少 key 值提示的补充

2,721 阅读1分钟

项目中使用多语言 t 函数传入 key 时,没有什么提示,使用 ts 突然不适的感觉,还要去看一眼多语言的 json 文件中是否有没有这个 key,不然传入一个空或者不存在的都不会报错

image.png

希望能如下图,能有个报错提示,

image.png

解决方式

查找 react-i18next 文档存在搭配 typescript 的描述:文档地址:react.i18next.com/latest/type…

  • 创建一个 react-i18next.d.ts 文件声明,复制一下

官方代码

// import the original type declarations
import 'react-i18next';
// import all namespaces (for the default language, only)
import ns1 from 'locales/en/ns1.json';
import ns2 from 'locales/en/ns2.json';


// react-i18next 版本 低于 11.11.0 的写法
declare module 'react-i18next' {
  // and extend them!
  interface Resources {
    ns1: typeof ns1;
    ns2: typeof ns2;
  }
}

// react-i18next 版本 高于 11.11.0 的写法
declare module 'react-i18next' {
  // and extend them!
  interface CustomTypeOptions {
    // custom namespace type if you changed it
    defaultNS: 'ns1';
    // custom resources type
    resources: {
      ns1: typeof ns1;
      ns2: typeof ns2;
    };
  };
};

个人代码

i18n.ts 文件

// => i18n.ts 文件
import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';
import cn from './zh-CN.json';
import en from './en-US.json';

export enum LanguageType {
  ZH_CN = 'zh-CN',
  EN_US = 'en-US',
}

export const resources = {
  [LanguageType.ZH_CN]: {
    translation: cn,
  },
  [LanguageType.EN_US]: {
    translation: en,
  },
};

let language = LanguageType.ZH_CN;

// todo: 待引入判断系统语言处理,见人说人话,见鬼说鬼话

i18next.use(initReactI18next).init({
  resources,
  lng: language,
  detection: {
    caches: ['localStorage'],
  },
});

export default i18next;

react-i18next.d.ts 文件

// => react-i18next.d.ts 文件
import { resources, LanguageType } from '@render/locales';

// 解决 i18next.t 函数没有的提示
type I18nStoreType = typeof import('@render/locales/zh-CN.json');

export type I18nT = {
  (key: keyof I18nStoreType): string;
};

declare module 'i18next' {
  // eslint-disable-next-line @typescript-eslint/no-empty-interface
  interface TFunction extends I18nT {}
}

declare module 'react-i18next' {
  interface CustomTypeOptions {
    resources: typeof resources[LanguageType.ZH_CN];
  }
}

最后的效果

  • 对应的 key 值提示 image.png
  • 对应的报错提示 image.png