【发布时间】:2021-11-21 20:39:54
【问题描述】:
我有这个示例 TypeScript 代码,它应该将简单的 JSON 反序列化为 Person 类的实例,然后对其调用 foo 方法,但它不起作用:
class Person {
name!: string;
age!: number;
foo() {
console.log("Hey!");
}
}
fetch("/api/data")
.then(response => {
return response.json() as Promise<Person>;
}).then((data) => {
console.log(data);
data.foo();
});
控制台的输出显示该对象的形状正确,但它未被识别为Person:
Object { name: "Peter", age: 44 }
age: 44
name: "Peter"
因此,当它尝试调用 foo 方法时失败:
Uncaught (in promise) TypeError: data.foo is not a function
http://127.0.0.1:8000/app.js:14
承诺回调* http://127.0.0.1:8000/app.js:12
我该如何解决?我应该使用 Object.assign 还是有其他更好的/native 解决方案?
let x = (<any>Object).assign(Object.create(Person.prototype), data);
x.foo();
【问题讨论】:
标签: json typescript serialization deserialization