如何在TypeScript(Angular)中为JSON格式创建对应Interface
首先我们从嵌套层级最低的结构开始逐层定义TypeScript接口即可,注意你提供的JSON示例里,第二个player的age字段为空字符串,和第一个的数字类型不一致,定义的时候可以根据实际业务情况选择联合类型或者修正为单一类型。
完整的interface定义如下:
// 球员信息结构 interface Player { id: number; name: string; // 若实际业务中age仅为数字,可直接改为 age: number; age: number | string; gender: string; } // 足球俱乐部结构 interface FootballClub { id: number; club: string; address: string; players: Player[]; } // 最外层返回数据结构 interface RootResponse { football: FootballClub[]; }
在Angular中使用时,可以直接将接口作为HttpClient请求的泛型参数,获得完整的类型提示:
import { HttpClient } from '@angular/common/http'; // ...构造函数注入httpClient逻辑略 this.http.get<RootResponse>('你的请求接口地址').subscribe(data => { // 此处访问data的属性会自动触发类型校验和提示 const firstClubName = data.football[0].club; const firstPlayerName = data.football[0].players[0].name; })
内容的提问来源于stack exchange,提问作者saajan-pixel
相关产品推荐
相关产品推荐

