将 JSON 配置动态转换为打字稿类



我在网上搜索过,我阅读了打字稿文档,并查看了许多关于堆栈溢出的答案。没有人在以下方面给我足够的见解:

使用打字稿,我导入了一个如下所示的JSON文件:

[
{
"property" : "FristName",
"type" : "string"
},
{
"property" : "LastName",
"type" : "string"
},
{
"property" : "Age",
"type" : "number"
}
]

property键是class propertytype键表示property type

然后我尝试编写一个类构造函数,在运行时将其动态转换为:

class Person {
public FirstName: string;
public LastName: string;
public Age: number
{

JSON array可能具有n对象文本的索引。对象文字结构是静态的,始终只有两个属性attributetype

一个好的做法是创建一个PersonFactory类,使用接受 JSON 字符串并返回 Person 实例的公共fromJSON方法。

import { Person } from "person";
export interface Spec {
[index: number]: {attribute: string, type: "string" | string };
}
export class PersonFactory {
fromJSON(spec: Spec): Person {
return new Person(spec[0].attribute, spec[1].attribute);
}
}

将工厂用作:

import { PersonFactory, Spec } from "factories";
const data: Spec = require("person_spec.json");
const person: Person = (new PersonFactory()).fromJSON(data);

最新更新