【问题标题】:Creation of Interface for json Format in TypeScript (angular)在 TypeScript 中创建 json 格式的接口(角度)
【发布时间】:2026-01-26 00:20:03
【问题描述】:

我是 JSON 格式的接口创建新手。如何在 TypeScript (Angular) 中为以下 JSON 创建interface

{
    "football": [
        {
          "id": 1,
          "club": "dfgz",
          "address": "adfs",
          "players": [
            {
              "id": 1,
              "name": "dsaf",
              "age": 4,
              "gender": ""
            },
            {
              "id": 2,
              "name": "",
              "age": "",
              "gender": ""
            }
          ]
        }
      ]
}

【问题讨论】:

  • 最简单的入门方法是转到app.quicktype.io 并在其中输入您的JSON,您显示的不是完整的sn-p,所以很难说。你试过什么?你有什么困难?所有现有答案都是有效的,因为您没有解释您的问题实际上是什么。

标签: json angular typescript


【解决方案1】:

你可以这样做:

interface Sport {[sport: string]: {
    id: number, club: string, address: string, players: {
            id: number, name: string, age: number, gender: string
        }[]
    }[]
}

【讨论】:

    【解决方案2】:

    像这样:

    export interface Player {
      id: number;
      name: string;
      age: string;
      gender: string;
    }
    export interface FootballClub {
     id: number;
     club: string;
     address: string;
     players: Player[];
    }
    

    【讨论】:

      【解决方案3】:
      export interface Game {
       [key: string]: SportInfo[];
      }
      
      export interface SportInfo {
         id: number;
         club: string;
         address: string;
         players: Player[];
      }
      export interface Player {
         id: number;
         name: string;
         age: number | string;
         gender: string;
      }
      

      可以像这样使用

      let footballSport: Game = {
       football: [ { "id": 1, "club": "dfgz", "address": "adfs", "players": [ { "id": 1, "name": "dsaf", "age": 4, "gender": "" }, { "id": 2, "name": "", "age": "", "gender": "" } ] } ]
      

      【讨论】:

      • 这会失败,有些年龄是字符串,有些是数字。
      • 年龄不应该是字符串。
      • 也许不应该,但从示例 JSON 来看,它可以!我不确定你的论点是什么。
      【解决方案4】:
      export interface IFootballPlayer {
        id: number;
        name: string;
        age: number | string;
        gender: string;
      }
      
      export interface IFootballClub {
        id: number;
        club: string;
        address: string;
        players: IFootballPlayer[];
      }
      

      然后在你的 TypeScript 中你会这样做:

      footballClubs: IFootballClub[] = [ { "id": 1, "club": "dfgz", "address": "adfs", "players": [ { "id": 1, "name": "dsaf", "age": 4, "gender": "" }, { "id": 2, "name": "", "age": "", "gender": "" } ] } ]
      

      【讨论】: