TypeScript如何将自定义类分配给JSON对象数组
TypeScript 普通JSON数组转指定类实例数组实现方案
首先明确核心注意点:
- 直接使用
as Report[]做类型断言仅能通过TS静态类型检查,运行时不会生成真正的类实例,JSON解析出的时间字段仍是字符串类型,无法调用Date类的原型方法。 - 你当前场景下JSON结构和Report类属性完全匹配,只需要在转换时手动将时间字符串转为
Date实例即可。
方案1:给类添加构造函数(推荐,代码复用性高)
修改Report类添加构造函数,接收普通JSON对象做初始化,后续直接遍历数组调用构造函数生成实例即可:
export class Report { created_at!: Date; updated_at!: Date; constructor(jsonData: { created_at: string; updated_at: string }) { // 手动将字符串格式的时间转为Date实例 this.created_at = new Date(jsonData.created_at); this.updated_at = new Date(jsonData.updated_at); } } // 转换逻辑 const reportInstances: Report[] = jsonBody.map(item => new Report(item));
方案2:不修改原有类定义的无侵入转换
如果不想改动原有Report类的代码,可以在遍历逻辑中手动给实例赋值:
// 保留原有Report类定义不变 export class Report { created_at!: Date; updated_at!: Date; } // 转换逻辑 const reportInstances: Report[] = jsonBody.map(item => { const report = new Report(); report.created_at = new Date(item.created_at); report.updated_at = new Date(item.updated_at); return report; });
转换结果验证
转换完成后可以通过以下方式确认结果符合预期:
console.log(reportInstances[0] instanceof Report); // 输出 true console.log(reportInstances[0].created_at instanceof Date); // 输出 true console.log(reportInstances[0].created_at.getFullYear()); // 正常输出 2016,无类型报错
避坑提示:如果后续类新增了其他引用类型属性(比如嵌套的自定义类、数组等),需要在转换时同步对这些属性做实例化处理,不要直接赋值JSON里的普通对象。
内容的提问来源于stack exchange,提问作者J L
相关产品推荐
相关产品推荐

