瀏覽代碼

feat: i18n $t方法支持ts类型提示

dap 4 月之前
父節點
當前提交
76f4824d2b
共有 2 個文件被更改,包括 20 次插入2 次删除
  1. 4 2
      src/lang/index.ts
  2. 16 0
      src/types/module.d.ts

+ 4 - 2
src/lang/index.ts

@@ -2,8 +2,8 @@
 import { createI18n } from 'vue-i18n';
 
 import { LanguageEnum } from '@/enums/LanguageEnum';
-import zh_CN from "@/lang/zh_CN";
-import en_US from "@/lang/en_US";
+import zh_CN from '@/lang/zh_CN';
+import en_US from '@/lang/en_US';
 
 /**
  * 获取当前语言
@@ -29,3 +29,5 @@ const i18n = createI18n({
 });
 
 export default i18n;
+
+export type LanguageType = typeof zh_CN;

+ 16 - 0
src/types/module.d.ts

@@ -8,6 +8,7 @@ import { useDict } from '@/utils/dict';
 import { handleTree, addDateRange, selectDictLabel, selectDictLabels, parseTime } from '@/utils/ruoyi';
 import { getConfigKey, updateConfigByKey } from '@/api/system/config';
 import { download as rd } from '@/utils/request';
+import type { LanguageType } from '@/lang';
 
 export {};
 
@@ -20,6 +21,11 @@ declare module '@vue/runtime-core' {
     $auth: typeof auth;
     $cache: typeof cache;
     animate: typeof animate;
+    /**
+     * i18n $t方法支持ts类型提示
+     * @param key i18n key
+     */
+    $t(key: ObjKeysToUnion<LanguageType>): string;
 
     useDict: typeof useDict;
     addDateRange: typeof addDateRange;
@@ -33,6 +39,16 @@ declare module '@vue/runtime-core' {
   }
 }
 
+/**
+ * { a: 1, b: { ba: { baa: 1, bab: 2 }, bb: 2} } ---> a | b.ba.baa | b.ba.bab | b.bb
+ * https://juejin.cn/post/7280062870670606397
+ */
+export type ObjKeysToUnion<T, P extends string = ''> = T extends object
+  ? {
+      [K in keyof T]: ObjKeysToUnion<T[K], P extends '' ? `${K & string}` : `${P}.${K & string}`>;
+    }[keyof T]
+  : P;
+
 declare module 'vform3-builds' {
   const content: any;
   export = content;