如何根据API返回的嵌套JSON数据创建对应的TypeScript类
Angular调用API返回嵌套JSON的TypeScript类型定义方案
结论
嵌套结构需要定义对应的独立类型,如果你的模型仅用于做数据类型约束、不需要添加自定义业务方法,优先使用更轻量的interface,如果需要封装方法再使用class。
具体声明代码
第一步:定义通用ID结构
所有包含ID字段的嵌套对象结构完全一致,可以提取为通用类型:
export interface IdObject { ID: string; }
第二步:定义PermissionProfile类型
export interface PermissionProfile { Name: string; PermissionProfileId: IdObject; Type: number; }
第三步:定义完整的员工类型
export interface Employee { AccessGroupsIdList: string[]; FirstName: string; LastName: string; // 注意:原代码写的是number[],如果API返回的是字符串格式的UUID,建议改为string[] LocationIdList: string[]; PermissionProfile: PermissionProfile; ManagerName: string; Status: boolean; UserGroupID: IdObject; UserGroupName: string; UserId: IdObject; }
调用示例
Angular中调用API时直接指定返回类型即可获得完整的类型提示:
import { HttpClient } from '@angular/common/http'; import { Employee } from './employee.model'; // 注入HttpClient后调用 this.http.get<Employee[]>('你的外部API地址').subscribe(employeeList => { // 嵌套字段也会有自动补全和类型校验 console.log(employeeList[0].PermissionProfile.Name); console.log(employeeList[0].UserId.ID); });
若需要使用class的写法
如果需要在模型中添加自定义方法,可以替换为class声明:
class IdObject { ID: string; constructor(id: string) { this.ID = id; } } class PermissionProfile { Name: string; PermissionProfileId: IdObject; Type: number; constructor(data: any) { this.Name = data.Name; this.PermissionProfileId = new IdObject(data.PermissionProfileId.ID); this.Type = data.Type; } // 可添加自定义方法 getProfileType() { return this.Type === 3 ? 'Agent' : 'Other'; } } export class Employee { AccessGroupsIdList: string[]; FirstName: string; LastName: string; LocationIdList: string[]; PermissionProfile: PermissionProfile; ManagerName: string; Status: boolean; UserGroupID: IdObject; UserGroupName: string; UserId: IdObject; constructor(data: any) { this.AccessGroupsIdList = data.AccessGroupsIdList || []; this.FirstName = data.FirstName; this.LastName = data.LastName; this.LocationIdList = data.LocationIdList || []; this.PermissionProfile = new PermissionProfile(data.PermissionProfile); this.ManagerName = data.ManagerName; this.Status = data.Status; this.UserGroupID = new IdObject(data.UserGroupID.ID); this.UserGroupName = data.UserGroupName; this.UserId = new IdObject(data.UserId.ID); } }
内容的提问来源于stack exchange,提问作者SilverFish
相关产品推荐
相关产品推荐

