我想创建文件工厂(例如在我的情况下带有翻译的JSON)。
{
"field": "",
"group": {
"field_1": "",
"field_2": ""
},
...
}
我希望创建一个模板JSON,其中包含我的翻译中存在的所有字段,然后使用每个语言环境的一些默认值对其进行实例化,以使我的应用程序不会错过任何翻译字段。嗯,这很简单,在输出中我有几个文件(基于语言环境的数量),名为<locale>.json
,例如en.json
有这样的内容:
{
"field": "en:field",
"group": {
"field_1": "en:group.field_1",
"field_2": "en:group.field_2",
},
...
}
现在我想基于我的JSON模板创建一个类型或接口,以允许我的翻译字段显示在我的IDE的快速建议中(例如VS代码)。
有没有可能以方便的方式做到这一点?我知道我可以使用导出的接口动态创建一个.ts
文件,但这不是很好,因为所有ts
语法都将通过字符串提供,因此在创建过程中可能会出现一些错误。可能有任何合法途径吗?
要清楚,我希望得到这样的界面
interface IMyCoolInterface {
field: string,
group: {
field_1: string,
field_2: string,
},
...
}
您可以使用TypeScript 2.9中引入的--resolveJsonModule
compiler option。然后您可以将模板文件导入为模块:
import * as translationTemplate from 'template.json';
并使用typeof
type query为其定义类型:
type Translation = typeof translationTemplate;
如果一切顺利,如果您声明变量为Translation
类型,您应该获得IDE提示:
declare const t: Translation; // or whatever
t.field; // hinted at you
t.group.field_1; // likewise
希望有所帮助。祝好运!
我认为一个好的解决方案是:
一个简单实现的例子是:
interface IGroup{
field_1:string;
field_2:string;
}
interface IMyCoolInterface{
field:string;
group:IGroup;
}
如果你想要一组JSON数组:
interface IMyCoolInterface{
field:string;
groups:Array<IGroup>;
}
现在,您必须实现如下界面:首先实现IGroup接口:
class Group implements IGroup{
field_1:string;
field_2:string;
construdtor(field_1:string,field_2:string)
{
this.field_1=field_1;
this.field_2=field_2;
}
}
现在实现IMyCoolInterface(假设您需要一组JSON数组):
class MyCoolClass implements IMyCoolInterface
{
field:string;
groups:Array<IGroup>;
constructor(field:string,groups?:Array<IGroup>)
{
this.field=field;
this.groups=groups || [];
}
//add some methods
addGroup(group:IGroup)
{
this.groups.push(group)
}
}
这是使用接口处理JSON的简单方法。