繁体   English   中英

TypeScript:基于object创建接口

[英]TypeScript: Create interface based on object

我想创建文件工厂(例如 JSON 与我的情况下的翻译)。

{
    "field": "",
    "group": {
        "field_1": "",
        "field_2": ""
    },
    ...
}

我希望创建一个模板 JSON,其中包含我的翻译中存在的所有字段,然后使用每个语言环境的一些默认值对其进行实例化,以使我的应用程序不会错过任何翻译字段。 好吧,这很简单,在 output 我有几个文件(基于语言环境的数量),名为<locale>.json ,例如en.json ,其中包含以下内容:

{
    "field": "en:field",
    "group": {
        "field_1": "en:group.field_1",
        "field_2": "en:group.field_2",
    },
    ...
}

现在我想基于我的 JSON 模板创建一个类型或接口,以允许我的翻译字段显示在我的 IDE(例如 VS Code)的快速建议中。

有没有可能以方便的方式做到这一点? 我知道我可以动态创建一个导出接口的.ts文件,但这不是很好,因为所有ts语法都将通过字符串提供,因此在创建过程中可能会出现一些错误。 可能有什么合法的途径吗?

说清楚,我想得到这样的界面

interface IMyCoolInterface {
    field: string,
    group: {
        field_1: string,
        field_2: string,
    },
    ...
}

您可以使用 TypeScript 2.9 中引入的--resolveJsonModule编译器选项 然后您可以将模板文件作为模块导入:

import * as translationTemplate from 'template.json';

并使用typeof类型查询为其定义类型

type Translation = typeof translationTemplate;

如果一切顺利,如果您将变量声明为Translation类型,您应该会得到 IDE 提示:

declare const t: Translation; // or whatever
t.field; // hinted at you
t.group.field_1; // likewise

希望有帮助。 祝你好运!

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

  • 首先根据您的 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 的一种简单方法。

是的,在打字稿中是可能的,

type Tob = typeof ob;

var ob = {
  a: 1,
  b: 'string',
};

你不需要任何额外的标志,我仍然会粘贴在我的 tsconfig.json 下面

在此处输入图片说明

// my tsconfig.json
{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}

There are several IDE plugins based on the json2ts library that allow you to paste in a JSON object and get back a Typescript interface for that object.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM