[英]Generate Interface from an object in Typescript
我有一个Typescript
项目,我想从object
中的数据生成一个Interface
,我不知道这是否可能,但我做不到。
我所做的是:
JSON
数据库 Object 和查询结果这是我从数据库中得到的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.