繁体   English   中英

从 Typescript 中的 object 生成接口

[英]Generate Interface from an object in Typescript

我有一个Typescript项目,我想从object中的数据生成一个Interface ,我不知道这是否可能,但我做不到。

我所做的是:

  1. 我得到JSON数据库 Object 和查询结果
  2. 根据 object 的值,我需要创建一个动态接口以将 ArrayList 添加到每个值,从而避免每次数据库值更改时都修改接口

这是我从数据库中得到的object

interface Auto {
  autoType: string
}
let autoActive: Auto[] = [
  {  "autoType": "Car"},
  {  "autoType": "Motorcycle"},
  {  "autoType": "Truck"},
  {  "autoType": "Plane"}
]

console.log(autoActive.map(Object.values).toString()); // Car,Motorcycle,Truck,Plane

这是我需要从genericObject model 的上述数据 ( AutoBrand ) 创建的interface

interface genericObject {
  [key: string]: any;
}
interface AutoBrand extends genericObject {
  "Car": Array<string>,
  "Motorcycle": Array<string>,
  "Truck": Array<string>,
  "Plane": Array<string>
}

我想从这里获得的是生成一个常量object来为每个最终文件分配标题,这是我想要获得的最终 class 的示例,然后从这里提取标题:

export class HeaderConst {
  static readonly headerConst: AutoBrand = {
    "Car": [
      "Model",
      "Total",
      "Age"
    ],
    "Motorcycle": [
      "Model",
      "Total",
      "Age"
    ],
    "Truck": [
      "Model",
      "Total",
      "Age"
    ],
    "Plane": [
      "Model",
      "Total",
      "Age"
    ]
  }
  public static getConstants(elem: string) {
    return elem.split(".").reduce((elm: any, i: any) => {
        return elm[i];
    }, this.headerConst);
  }
}

那是不可能的。 你的JSON只在运行时存在,而TypeScript接口在运行时根本不存在。

暂无
暂无

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

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