我有一个类,里面有多个接口来对JSON数据进行建模。例如:
interface A {
id: number;
}
interface B {
name: string;
surname?: string;
}
class MyClass implements A {
people: B[];
notes: string[];
function1(){...}
function2(){...}
}
我有一个结构相同的 JSON:
{
id: 1,
people: [
{
name: "john"
},
{
name: "alice",
surname: "smith"
}
],
notes: [ "Very important top secret note" ]
}
是否可以直接从此 JSON 创建MyClass
实例?
你的数据结构与你的类几乎相同,你必须向类添加一个id属性
class MyClass implements A {
id: number;
// ....
}
问题是,如果您尝试执行以下操作:
let data: MyClass = {
id: 1,
people: [
{
name: "john"
},
{
name: "alice",
surname: "smith"
}
],
notes: [ "Very important top secret note" ]
}
这不起作用,因为您的 json 没有方法(函数 1、函数 2(。
一种解决方案是真正实例化MyClass并传递json,或者有一个构造函数方法,例如
class MyClass {
static createFrom(jsonData: A & B): MyClass {
// create the objct and return
}
}
或者,您可以通过组合类的现有实例并传播 json 来创建该类型的变量。
这样:
let json = {
id: 1,
people: [
{
name: "john"
},
{
name: "alice",
surname: "smith"
}
],
notes: ["Very important top secret note"]
}
const c = new MyClass();
let mClass: MyClass = {...json, function1: c.function1, function2: c.function2 };
mClass.function1();
链接到游乐场