TypeScript:基于对象创建接口

问题描述 投票:0回答:2

我想创建文件工厂(例如在我的情况下带有翻译的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,
    },
    ...
}
javascript node.js typescript
2个回答
3
投票

您可以使用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

希望有所帮助。祝好运!


1
投票

我认为一个好的解决方案是:

  • 首先根据您的JSON数据结构声明一个接口(或接口)
  • 其次,您可以实现界面,甚至可以根据需要添加一些方法。

一个简单实现的例子是:

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的简单方法。

© www.soinside.com 2019 - 2024. All rights reserved.