我目前正在开发一个大量使用国际化(i18n)的网络项目,我很难弄清楚如何确保所有语言共享完全相同的键。
这是一个简单的src/lang/en.ts
文件示例:
export default {
title: "My Website Project",
description: "This is an example of a file which contains phrases and their keys",
hello: "Hello!",
};
这是一个简单的src/lang/id.ts
文件示例:
export default {
title: "Proyek Website Saya",
description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
hello: "Halo!",
};
现在,我希望 TypeScript 确保这些文件具有相同的键(不多也不少)。因此,如果我将cat
属性放入src/lang/id.ts
,则:
export default {
title: "Proyek Website Saya",
description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
hello: "Halo!",
cat: "Kucing", // <-- this must be error because "cat" doesn't exist in en.ts file!
};
但我无法建立这样的界面
export default interface LanguageStruct {
title: string,
description: string,
hello: string,
};
因为在实际项目中每种语言都有数百个短语,并且一个接一个地编写这些键既费时又费力。我想知道 TypeScript 是否有解决这个问题的技巧,或者至少有某种自动化来完成这项工作。
用于keyof typeof someObject
从对象的键(例如第一语言字符串)构造类型。然后限制您的其他对象(其他语言)将该类型作为键,并将字符串作为值,使用Record
. 所以你要找的类型是Record<keyof typeof someObject, string>
. 例子:
const en = {
title: "My Website Project",
description: "This is an example of a file which contains phrases and their keys",
hello: "Hello!",
};
const de: Record<keyof typeof en, string> = {
title: "Proyek Website Saya",
description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
hello: "Halo!",
cat: "Kucing", // this is highlighted as an error
};
请参阅此处的工作示例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句