【发布时间】:2018-02-10 19:07:07
【问题描述】:
使用 ES5 将 JSON 转换为 Typescript 类的最佳/常用方法是什么(没有 Object.assign())。
例如
export class Lesson{
name:string;
teacher:Teacher;
date:Date;
scholars:Array<string>; //or string[] ... I dont care
}
JSON 看起来像:
{
name:"LessonName",
teacher:{name:"masterT", age:120},
date:12345678912
scholars:["Jim","Bob","Jimbo"]
}
在 Typescript 中,我可以将 JSON 转换为对象,甚至将其直接分配给课程对象(!-可怕的行为,但那是 JS-!)
但是对象没有任何方法例如。
例如所以lesson.date.getTime() 不起作用。
那么如何正确处理呢?
【问题讨论】:
-
这是一个班级
constructor的工作。这样您就可以将日期字段转换为 Date 对象等,这样您就可以做到new Lesson(attributes)
标签: javascript json typescript